<?php
// Enable error reporting for debugging
error_reporting(E_ALL);
ini_set('display_errors', 1);

include '../includes/auth.php';
include '../includes/db.php';

$message = '';

// Handle event selection
$selected_event_id = $_GET['event_id'] ?? '';
$heats_total = 0;
$heat_settings = [];
$event_categories = [];

// Handle saving settings (only for selected event)
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_GET['event_id']) && isset($_POST['save_settings'])) {
    $event_id = intval($_POST['event_id']);
    
    // First, deactivate all heats and runs for this event (set to pending if not finished/cancelled)
    $pdo->prepare("UPDATE event_heat_settings SET is_active = 0, active_run = 0, status = 'pending' WHERE event_id = ? AND status NOT IN ('finished', 'cancelled')")->execute([$event_id]);
    
    if (isset($_POST['heat_name'])) {
        foreach ($_POST['heat_name'] as $heat_number => $name) {
            $heat_name = trim($name);
            $scoring_type = $_POST['scoring_type'][$heat_number] ?? 'Points';
            $runs_count = intval($_POST['runs_count'][$heat_number] ?? 1);
            $runs_scoring_method = $_POST['runs_scoring_method'][$heat_number] ?? 'best_from_all';
            $time_start = $_POST['time_start'][$heat_number] ?? null;
            $estimate_time_per_participant = intval($_POST['estimate_time_per_participant'][$heat_number] ?? 0);
            
            // Handle multiple categories
            $categories = isset($_POST['categories'][$heat_number]) ? $_POST['categories'][$heat_number] : [];
            $categories_json = json_encode($categories);
            
            // Handle format-related settings
            $format_name = $_POST['format_name'][$heat_number] ?? ($event_data['format_name'] ?? '');
            $discipline = $_POST['discipline'][$heat_number] ?? ($event_data['discipline'] ?? '');
            $difficulty_level = $_POST['difficulty_level'][$heat_number] ?? '';
            $course_length = intval($_POST['course_length'][$heat_number] ?? 0);
            $time_limit = intval($_POST['time_limit'][$heat_number] ?? 0);
            $weather_dependent = isset($_POST['weather_dependent'][$heat_number]) ? 1 : 0;
            $format_description = $_POST['format_description'][$heat_number] ?? '';
            $scoring_method = $_POST['scoring_method'][$heat_number] ?? 'standard';
            $required_figures = isset($_POST['required_figures'][$heat_number]) ? 
                                json_encode($_POST['required_figures'][$heat_number]) : '[]';
            $judges_required = intval($_POST['judges_required'][$heat_number] ?? 5);
            $scale_min = floatval($_POST['scale_min'][$heat_number] ?? ($event_data['scale_min'] ?? 0));
            $scale_max = floatval($_POST['scale_max'][$heat_number] ?? ($event_data['scale_max'] ?? 100));
            $precision_decimal = intval($_POST['precision_decimal'][$heat_number] ?? ($event_data['precision_decimal'] ?? 0));
            
            // Handle flow settings - only process if not disabled
            $flow_type = $_POST['flow_type'][$heat_number] ?? 'none';
            $flow_source_heat = null;
            $flow_participants_per_category = 0;
            $flow_position_range = null;
            
            if ($flow_type !== 'none') {
                // Support multiple source heats (array or single value)
                $source_heat_input = $_POST['flow_source_heat'][$heat_number] ?? null;
                
                if ($source_heat_input) {
                    // If it's already an array (from multiselect)
                    if (is_array($source_heat_input)) {
                        $flow_source_heat = json_encode(array_map('intval', array_filter($source_heat_input)));
                    } else {
                        // Single value - convert to JSON array for consistency
                        $flow_source_heat = json_encode([intval($source_heat_input)]);
                    }
                }
                
                $flow_participants_per_category = intval($_POST['flow_participants_per_category'][$heat_number] ?? 0);
                $flow_position_range = trim($_POST['flow_position_range'][$heat_number] ?? '');
                
                // Validate position range format (e.g., "1-3", "4-8")
                if (!empty($flow_position_range) && !preg_match('/^\d+-\d+$/', $flow_position_range)) {
                    $flow_position_range = null; // Invalid format
                }
                
                // Validate flow settings
                if ($flow_participants_per_category < 1) {
                    $flow_participants_per_category = 0;
                    $flow_type = 'none'; // Reset to none if invalid
                }
                
                if ($flow_type === 'promotion' && !$flow_source_heat) {
                    $flow_type = 'none'; // Reset to none if no source heat selected
                }
            }
            
            $is_active = isset($_POST['is_active']) && $_POST['is_active'] == $heat_number ? 1 : 0;
            $active_run = 0;
            
            // Determine heat status
            $status = 'pending'; // Default status
            if (isset($_POST['heat_status'][$heat_number])) {
                $status = $_POST['heat_status'][$heat_number];
            } elseif ($is_active) {
                $status = 'active';
            }
            
            // If heat is active, set the active run
            if ($status === 'active' && isset($_POST['active_run'][$heat_number])) {
                $active_run = intval($_POST['active_run'][$heat_number]);
            }
            
            // Process heat-specific scoring layout configuration
            $heat_scoring_layout_config = null;
            if (isset($_POST['heat_scoring_layout'][$heat_number])) {
                $heatLayoutData = $_POST['heat_scoring_layout'][$heat_number];
                
                // Handle checkboxes - unchecked checkboxes don't appear in POST data
                $availableComponents = [
                    'criteriaInputGrid', 'finalCalculatedScore', 'figuresCard', 
                    'latestScores', 'otherHeatScores', 'diversityValidation', 
                    'figureHistory', 'formatInfo'
                ];
                
                // Ensure all components have an enabled status (default false if not present)
                if (isset($heatLayoutData['cards'])) {
                    foreach ($availableComponents as $component) {
                        if (!isset($heatLayoutData['cards'][$component]['enabled'])) {
                            $heatLayoutData['cards'][$component]['enabled'] = false;
                        } else {
                            // Convert string "1" to boolean true
                            $heatLayoutData['cards'][$component]['enabled'] = 
                                ($heatLayoutData['cards'][$component]['enabled'] == '1');
                        }
                    }
                }
                
                // Convert layout options to proper types
                if (isset($heatLayoutData['layout']['compactMode'])) {
                    $heatLayoutData['layout']['compactMode'] = 
                        ($heatLayoutData['layout']['compactMode'] == '1');
                }
                if (isset($heatLayoutData['layout']['hideEmptyCards'])) {
                    $heatLayoutData['layout']['hideEmptyCards'] = 
                        ($heatLayoutData['layout']['hideEmptyCards'] == '1');
                }
                
                $heat_scoring_layout_config = json_encode($heatLayoutData);
            }
            
            $stmt = $pdo->prepare("
                INSERT INTO event_heat_settings (
                    event_id, heat_number, heat_name, scoring_type, runs_count, runs_scoring_method,
                    time_start, estimate_time_per_participant, categories, 
                    flow_type, flow_source_heat, flow_participants_per_category, flow_position_range,
                    is_active, active_run, status,
                    format_name, discipline, difficulty_level, course_length, time_limit,
                    weather_dependent, format_description, scoring_method, required_figures,
                    judges_required, scale_min, scale_max, precision_decimal, scoring_layout_config
                ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
                ON DUPLICATE KEY UPDATE 
                    heat_name = VALUES(heat_name),
                    scoring_type = VALUES(scoring_type),
                    runs_count = VALUES(runs_count),
                    runs_scoring_method = VALUES(runs_scoring_method),
                    time_start = VALUES(time_start),
                    estimate_time_per_participant = VALUES(estimate_time_per_participant),
                    categories = VALUES(categories),
                    flow_type = VALUES(flow_type),
                    flow_source_heat = VALUES(flow_source_heat),
                    flow_participants_per_category = VALUES(flow_participants_per_category),
                    flow_position_range = VALUES(flow_position_range),
                    is_active = VALUES(is_active),
                    active_run = VALUES(active_run),
                    status = VALUES(status),
                    format_name = VALUES(format_name),
                    discipline = VALUES(discipline),
                    difficulty_level = VALUES(difficulty_level),
                    course_length = VALUES(course_length),
                    time_limit = VALUES(time_limit),
                    weather_dependent = VALUES(weather_dependent),
                    format_description = VALUES(format_description),
                    scoring_method = VALUES(scoring_method),
                    required_figures = VALUES(required_figures),
                    judges_required = VALUES(judges_required),
                    scale_min = VALUES(scale_min),
                    scale_max = VALUES(scale_max),
                    precision_decimal = VALUES(precision_decimal),
                    scoring_layout_config = VALUES(scoring_layout_config),
                    updated_at = CURRENT_TIMESTAMP
            ");
            
            $stmt->execute([
                $event_id, $heat_number, $heat_name, $scoring_type, $runs_count, $runs_scoring_method,
                $time_start, $estimate_time_per_participant, $categories_json,
                $flow_type, $flow_source_heat, $flow_participants_per_category, $flow_position_range,
                $is_active, $active_run, $status,
                $format_name, $discipline, $difficulty_level, $course_length, $time_limit,
                $weather_dependent, $format_description, $scoring_method, $required_figures,
                $judges_required, $scale_min, $scale_max, $precision_decimal, $heat_scoring_layout_config
            ]);
        }
        $message = '<div class="alert alert-success"><i class="fas fa-check-circle me-2"></i>Heat settings saved successfully!</div>';
    }
}

// Handle deactivate request
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['deactivate_heat'])) {
    $event_id = intval($_POST['event_id']);
    $pdo->prepare("UPDATE event_heat_settings SET is_active = 0, active_run = 0, status = 'pending' WHERE event_id = ?")->execute([$event_id]);
    $message = '<div class="alert alert-info"><i class="fas fa-info-circle me-2"></i>All heats have been deactivated.</div>';
}

// Handle active run change request
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['change_active_run'])) {
    $event_id = intval($_POST['event_id']);
    $heat_number = intval($_POST['heat_number']);
    $direction = intval($_POST['direction']);
    
    // Get current active run
    $stmt = $pdo->prepare("SELECT active_run, runs_count FROM event_heat_settings WHERE event_id = ? AND heat_number = ? AND status = 'active'");
    $stmt->execute([$event_id, $heat_number]);
    $heat = $stmt->fetch(PDO::FETCH_ASSOC);
    
    if ($heat) {
        $current_run = intval($heat['active_run']);
        $runs_count = intval($heat['runs_count']);
        $new_run = $current_run + $direction;
        
        // Validate new run number
        if ($new_run >= 1 && $new_run <= $runs_count) {
            $update = $pdo->prepare("UPDATE event_heat_settings SET active_run = ? WHERE event_id = ? AND heat_number = ?");
            $update->execute([$new_run, $event_id, $heat_number]);
            $message = '<div class="alert alert-success"><i class="fas fa-check-circle me-2"></i>Active run changed to Run ' . $new_run . ' for Heat ' . $heat_number . '</div>';
        } else {
            $message = '<div class="alert alert-warning"><i class="fas fa-exclamation-triangle me-2"></i>Invalid run number. Must be between 1 and ' . $runs_count . '</div>';
        }
    } else {
        $message = '<div class="alert alert-danger"><i class="fas fa-times-circle me-2"></i>Heat ' . $heat_number . ' is not active.</div>';
    }
}

// Handle close heat request
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['close_heat'])) {
    $event_id = intval($_POST['event_id']);
    $heat_number = intval($_POST['heat_number']);
    
    // Set heat to finished status
    $update = $pdo->prepare("UPDATE event_heat_settings SET is_active = 0, active_run = 0, status = 'finished' WHERE event_id = ? AND heat_number = ?");
    $update->execute([$event_id, $heat_number]);
    
    $message = '<div class="alert alert-success"><i class="fas fa-check-circle me-2"></i>Heat ' . $heat_number . ' has been marked as finished.</div>';
}

// Handle cancel heat request
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['cancel_heat'])) {
    $event_id = intval($_POST['event_id']);
    $heat_number = intval($_POST['heat_number']);
    
    // Set heat to cancelled status
    $update = $pdo->prepare("UPDATE event_heat_settings SET is_active = 0, active_run = 0, status = 'cancelled' WHERE event_id = ? AND heat_number = ?");
    $update->execute([$event_id, $heat_number]);
    
    $message = '<div class="alert alert-warning"><i class="fas fa-ban me-2"></i>Heat ' . $heat_number . ' has been cancelled.</div>';
}

// Handle reschedule heat request
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['reschedule_heat'])) {
    $event_id = intval($_POST['event_id']);
    $heat_number = intval($_POST['heat_number']);
    
    // Set heat to rescheduled status
    $update = $pdo->prepare("UPDATE event_heat_settings SET is_active = 0, active_run = 0, status = 'rescheduled' WHERE event_id = ? AND heat_number = ?");
    $update->execute([$event_id, $heat_number]);
    
    $message = '<div class="alert alert-info"><i class="fas fa-clock me-2"></i>Heat ' . $heat_number . ' has been marked for rescheduling.</div>';
}

// Handle set pending heat request
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['set_pending_heat'])) {
    $event_id = intval($_POST['event_id']);
    $heat_number = intval($_POST['heat_number']);
    
    // Set heat to pending status
    $update = $pdo->prepare("UPDATE event_heat_settings SET is_active = 0, active_run = 0, status = 'pending' WHERE event_id = ? AND heat_number = ?");
    $update->execute([$event_id, $heat_number]);
    
    $message = '<div class="alert alert-secondary"><i class="fas fa-pause me-2"></i>Heat ' . $heat_number . ' has been set to pending status.</div>';
}

// Load events
$events = $pdo->query("SELECT id, name, heats_total FROM events ORDER BY date DESC")->fetchAll(PDO::FETCH_ASSOC);

// Load selected event settings
if ($selected_event_id) {
    $event = $pdo->prepare("
        SELECT e.*, sf.name as format_name, sf.sport as discipline, sf.mode as format_mode,
               sfj.scale_min, sfj.scale_max, sfj.scale_type, sfj.precision_decimal,
               GROUP_CONCAT(DISTINCT sfmc.config_value ORDER BY sfmc.config_key SEPARATOR ', ') as format_config
        FROM events e
        LEFT JOIN scoring_formats sf ON e.scoring_format = sf.format_id
        LEFT JOIN scoring_format_judges sfj ON sf.format_id = sfj.format_id
        LEFT JOIN scoring_format_mode_config sfmc ON sf.format_id = sfmc.format_id
        WHERE e.id = ?
        GROUP BY e.id
    ");
    $event->execute([$selected_event_id]);
    $event_data = $event->fetch(PDO::FETCH_ASSOC);
    $heats_total = intval($event_data['heats_total']);

    // Load event categories (main categories only)
    $categories_stmt = $pdo->prepare("
        SELECT id, category_name 
        FROM event_categories 
        WHERE event_id = ? AND is_main_category = 1 
        ORDER BY category_name
    ");
    $categories_stmt->execute([$selected_event_id]);
    $event_categories = $categories_stmt->fetchAll(PDO::FETCH_ASSOC);

    // Get participant counts per heat
    $participant_counts_stmt = $pdo->prepare("
        SELECT heat_number, COUNT(*) as participant_count 
        FROM event_participants 
        WHERE event_id = ? 
        GROUP BY heat_number
    ");
    $participant_counts_stmt->execute([$selected_event_id]);
    $heat_participant_counts = [];
    foreach ($participant_counts_stmt->fetchAll(PDO::FETCH_ASSOC) as $count_row) {
        $heat_participant_counts[$count_row['heat_number']] = $count_row['participant_count'];
    }
    
    // Load participants for bracket display
    $participants_stmt = $pdo->prepare("
        SELECT ep.heat_number, ep.bib_number, p.first_name, p.last_name, p.country
        FROM event_participants ep
        JOIN participants p ON ep.participant_id = p.id
        WHERE ep.event_id = ?
        ORDER BY ep.heat_number, ep.bib_number
    ");
    $participants_stmt->execute([$selected_event_id]);
    $heat_participants = [];
    foreach ($participants_stmt->fetchAll(PDO::FETCH_ASSOC) as $participant) {
        $heat_num = $participant['heat_number'];
        if (!isset($heat_participants[$heat_num])) {
            $heat_participants[$heat_num] = [];
        }
        $heat_participants[$heat_num][] = $participant;
    }

    // Load heat settings with new fields
    $settings = $pdo->prepare("
        SELECT heat_number, heat_name, scoring_type, runs_count, runs_scoring_method,
               time_start, estimate_time_per_participant, categories, flow_type, flow_source_heat,
               flow_participants_per_category, flow_position_range, is_active, active_run, status,
               format_name, discipline, difficulty_level, course_length, time_limit,
               weather_dependent, format_description, scoring_method, required_figures,
               judges_required, scale_min, scale_max, precision_decimal
        FROM event_heat_settings 
        WHERE event_id = ?
        ORDER BY heat_number
    ");
    $settings->execute([$selected_event_id]);
    foreach ($settings->fetchAll(PDO::FETCH_ASSOC) as $row) {
        $row['categories'] = json_decode($row['categories'] ?: '[]', true);
        $row['required_figures'] = json_decode($row['required_figures'] ?: '[]', true);
        $row['participant_count'] = $heat_participant_counts[$row['heat_number']] ?? 0;
        $heat_settings[$row['heat_number']] = $row;
    }
}
?>

<!DOCTYPE html>
<html>
<head>
    <title>Configure Heats</title>
    <!-- style skin holder -->
    <?php include_once '../includes/stylesheets.php'; ?>
</head>
<body class="body-bg-aurora-bright">
<?php include '../menu.php'; ?>
    
        
<div class="container-fluid container-StyleScore p-4">
        <!-- event action menu. -->
<div class="row mb-3">
    <div class="col-12">
        <?php       
        $use_localStorage = true;
        $show_header = false;
        //$show_public_view = false;
        include 'event_actions_menu.php'; 
        ?>
    </div>
</div>
	<div class="row justify-content-center">
            <div class="col-12">	
	
        <div class="d-flex justify-content-between align-items-center mb-4">
                <h2><i class="fas fa-fire me-2 text-warning"></i>Heat Configuration</h2>
                <div class="btn-group">
                        <?php if ($selected_event_id): ?>
                                <a href="heats_configure.php?event_id=<?= $selected_event_id ?>" class="btn btn-outline-primary">
                                        <i class="fas fa-users me-1"></i>Manage Participants
                                </a>
                                <a href="heat_flow_preview.php?event_id=<?= $selected_event_id ?>" class="btn btn-outline-info">
                                        <i class="fas fa-sitemap me-1"></i>Preview Flow
                                </a>
                        <?php endif; ?>
                        <button type="button" class="btn btn-outline-secondary ms-2" data-bs-toggle="modal" data-bs-target="#helpModal">
                                <i class="fas fa-circle-question me-1"></i>Help
                        </button>
                </div>
        </div>

        <!-- Help Modal -->
        <div class="modal fade" id="helpModal" tabindex="-1" aria-labelledby="helpModalLabel" aria-hidden="true">
            <div class="modal-dialog modal-xl modal-dialog-scrollable">
                <div class="modal-content">
                    <div class="modal-header">
                        <h5 class="modal-title" id="helpModalLabel"><i class="fas fa-circle-question me-2 text-info"></i>Configure Heats — Help</h5>
                        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                    </div>
                    <div class="modal-body p-0" style="height:80vh;">
                        <iframe src="../help/heats_configure_help.html" style="border:0;width:100%;height:100%;" title="Configure Heats Help"></iframe>
                    </div>
                </div>
            </div>
        </div>

        <!-- Activate Heat Modal -->
        <div class="modal fade" id="activateHeatModal" tabindex="-1" aria-labelledby="activateHeatModalLabel" aria-hidden="true">
            <div class="modal-dialog">
                <div class="modal-content">
                    <div class="modal-header bg-success text-white">
                        <h5 class="modal-title" id="activateHeatModalLabel">
                            <i class="fas fa-fire me-2"></i>Activate Heat <span id="activateHeatNumber"></span>
                        </h5>
                        <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Close"></button>
                    </div>
                    <div class="modal-body">
                        <!-- Active Heat Warning -->
                        <div id="activeHeatWarning" class="alert alert-warning d-none">
                            <i class="fas fa-exclamation-triangle me-2"></i>
                            <strong>Warning:</strong> Heat <span id="currentActiveHeatNumber"></span> (<span id="currentActiveHeatName"></span>) is currently active.
                            <br>Activating this heat will deactivate the current heat.
                        </div>

                        <!-- Run Selection -->
                        <div class="mb-3">
                            <label class="form-label fw-bold">
                                <i class="fas fa-play-circle me-1"></i>Select Run to Activate:
                            </label>
                            <div id="runSelectionOptions" class="d-grid gap-2">
                                <!-- Run buttons will be inserted here -->
                            </div>
                        </div>

                        <div class="alert alert-info mb-0">
                            <i class="fas fa-info-circle me-2"></i>
                            This will make <strong>Heat <span id="confirmHeatNumber"></span></strong> the active heat for scoring.
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">
                            <i class="fas fa-times me-1"></i>Cancel
                        </button>
                        <button type="button" class="btn btn-success" id="confirmActivateBtn" onclick="confirmActivateHeat()">
                            <i class="fas fa-fire me-1"></i>Activate Heat
                        </button>
                    </div>
                </div>
            </div>
        </div>

        <!-- Heat Results Modal -->
        <div class="modal fade" id="heatResultsModal" tabindex="-1" aria-labelledby="heatResultsModalLabel" aria-hidden="true">
            <div class="modal-dialog modal-fullscreen p-5">
                <div class="modal-content">
                    <div class="modal-header bg-info text-white">
                        <h5 class="modal-title" id="heatResultsModalLabel">
                            <i class="fas fa-trophy me-2"></i>Heat <span id="resultsHeatNumber"></span> - <span id="resultsHeatName"></span> Results
                        </h5>
                        <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Close"></button>
                    </div>
                    <div class="modal-body" style="max-height: 70vh; overflow-y: auto;">
                        <style>
                            #savedConfigsList .config-button {
                                font-size: 0.875rem;
                                padding: 0.5rem 0.75rem;
                                border-left: 3px solid transparent;
                                transition: all 0.2s;
                            }
                            #savedConfigsList .config-button:hover {
                                background-color: #f8f9fa;
                                border-left-color: #0dcaf0;
                            }
                            #savedConfigsList .config-button.active {
                                background-color: #e7f5ff;
                                border-left-color: #0dcaf0;
                                font-weight: 600;
                            }
                            #resultsContentDisplay table {
                                font-size: 0.875rem;
                            }
                            #resultsContentDisplay .table-hover tbody tr:hover {
                                background-color: rgba(13, 202, 240, 0.1);
                            }
                        </style>
                        <div class="row">
                            <!-- Sidebar with Configurations -->
                            <div class="col-md-3">
                                <div class="card shadow-sm mb-3">
                                    <div class="card-body p-3">
                                        <h6 class="mb-2 fw-bold text-success">
                                            <i class="fas fa-bookmark me-2"></i>Saved Reports
                                        </h6>
                                        <div id="savedConfigsList" class="list-group list-group-flush">
                                            <div class="text-center py-3 text-muted">
                                                <div class="spinner-border spinner-border-sm" role="status">
                                                    <span class="visually-hidden">Loading...</span>
                                                </div>
                                                <p class="mt-2 small">Loading configurations...</p>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            
                            <!-- Main Content Area -->
                            <div class="col-md-9">
                                <div id="resultsContentDisplay">
                                    <div class="alert alert-info mb-0">
                                        <i class="fas fa-info-circle me-2"></i>
                                        Select a report from the sidebar to view results.
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">
                            <i class="fas fa-times me-1"></i>Close
                        </button>
                    </div>
                </div>
            </div>
        </div>
    
    <?= $message ?>

    <div class="row">
        <div class="col-6">    
    <!-- Event Selection -->
    <form method="get" class="card p-2 mb-3 shadow-sm load-event-selection">
        <div class="d-flex align-items-center gap-2">
            <label class="form-label mb-0 fw-semibold text-primary">
                <i class="fas fa-calendar-alt me-1"></i>Select Event
            </label>
            <select class="form-select form-select-sm flex-grow-1" name="event_id" id="event_id" onchange="this.form.submit()">
                <option value="">-- Select Event --</option>
                <?php foreach ($events as $ev): ?>
                    <option value="<?= $ev['id'] ?>" <?= $ev['id'] == $selected_event_id ? 'selected' : '' ?>>
                        <?= htmlspecialchars($ev['name']) ?> (<?= $ev['heats_total'] ?> heats)
                    </option>
                <?php endforeach; ?>
            </select>
        </div>
    </form>
        </div>  
        <div class="col-6">    
<!-- Deactivate Section -->
        <?php 
        $active_heat = isset($heat_settings) ? array_filter($heat_settings, function($h) { return $h['status'] === 'active'; }) : [];
        if (!empty($active_heat)): 
        ?>
            <div class="alert alert-danger py-2 mb-3">
                <div class="d-flex justify-content-between align-items-center">
                    <div>
                        <h6 class="mb-1 text-danger">
                            <i class="fas fa-power-off me-1"></i>
                            Deactivate Current Heat
                        </h6>
                        <small class="text-muted">
                            Stop all heat activity and set event to inactive state
                        </small>
                    </div>
                    <form method="post">
                        <input type="hidden" name="event_id" value="<?= $selected_event_id ?>">
                        <input type="hidden" name="deactivate_heat" value="1">
                        <button type="submit" class="btn btn-outline-danger btn-sm" 
                                onclick="return confirm('Are you sure you want to deactivate the current heat? This will stop all scoring activity.')">
                            <i class="fas fa-stop me-1"></i>Deactivate
                        </button>
                    </form>
                </div>
            </div>
        <?php endif; ?>
        </div>  
    </div>
    <!-- Heat Settings -->
    <?php if ($selected_event_id && $heats_total): ?>
         <!-- Event Summary -->
        <div class="shadow-none card card-body mb-3 py-2">
            <h6 class="mb-2 text-info"><i class="fas fa-info-circle me-1"></i>Event Summary</h6>
            <div class="row g-2 small">
                <div class="col-md-3">
                    <strong>Total Heats:</strong> <?= $heats_total ?>
                </div>
                <div class="col-md-3">
                    <strong>Main Categories:</strong> <?= count($event_categories) ?>
                </div>
                <div class="col-md-3">
                    <?php 
                    $active_heat = array_filter($heat_settings, function($h) { return $h['is_active']; });
                    if ($active_heat): 
                        $active = array_values($active_heat)[0];
                    ?>
                        <strong>Active Heat:</strong> 
                        <span class="badge bg-success small">
                            <i class="fas fa-fire me-1"></i>
                            Heat <?= $active['heat_number'] ?> - Run <?= $active['active_run'] ?>
                        </span>
                    <?php else: ?>
                        <strong>Status:</strong> 
                        <span class="badge bg-secondary small">No Active Heat</span>
                    <?php endif; ?>
                </div>
                <div class="col-md-3">
                    <strong>Categories:</strong>
                    <?php if (empty($event_categories)): ?>
                        <a href="event_categories.php?event_id=<?= $selected_event_id ?>" class="btn btn-sm btn-warning py-0 px-2">
                            <i class="fas fa-plus me-1"></i>Add
                        </a>
                    <?php else: ?>
                        <span class="badge bg-success small"><?= count($event_categories) ?> Ready</span>
                    <?php endif; ?>
                </div>
            </div>
        </div>

      <!-- Configure Heats Section -->
    <div class=" shadow-none card p-4 shadow-sm mb-4">
        <div class="d-flex justify-content-between align-items-center mb-4">
            <h5 class="mb-0">
                <i class="fas fa-cogs me-2 text-success"></i>
                Configure <?= $heats_total ?> Heat<?= $heats_total > 1 ? 's' : '' ?>
               
            </h5>
            <div class="d-flex align-items-center gap-2">
                <small class="text-muted">Auto-refresh:</small>
                <select class="form-select form-select-sm" id="refreshInterval" style="width: auto;" onchange="setRefreshInterval()">
                    <option value="0">Manual</option>
                    <option value="5">5 seconds</option>
                    <option value="10">10 seconds</option>
                    <option value="30" selected>30 seconds</option>
                </select>
                <button type="button" class="btn btn-sm btn-outline-primary" onclick="loadHeatCards()" title="Refresh now">
                    <i class="fas fa-sync-alt me-1"></i>Refresh
                </button>
                <small class="text-muted" id="lastRefreshTime"></small>
            </div>
        </div>
        
        <?php 
        // Create an array to sort heats by flow order
        $heat_order = [];
        $processed_for_order = [];
        
        // First, add all starting heats (no incoming flow)
        for ($h = 1; $h <= $heats_total; $h++) {
            $setting = $heat_settings[$h] ?? [];
            $has_incoming = false;
            
            // Check if any other heat flows to this one
            foreach ($heat_settings as $other_setting) {
                if (($other_setting['flow_source_heat'] ?? null) == $h) {
                    $has_incoming = true;
                    break;
                }
            }
            
            // If no incoming flow and not a flow destination, it's a starting heat
            if (($setting['flow_type'] ?? 'none') === 'none' && !$has_incoming) {
                $heat_order[] = $h;
                $processed_for_order[] = $h;
            }
        }
        
        // Then add heats with flow connections in order
        $remaining_iterations = $heats_total;
        while (count($processed_for_order) < $heats_total && $remaining_iterations > 0) {
            for ($h = 1; $h <= $heats_total; $h++) {
                if (in_array($h, $processed_for_order)) continue;
                
                $setting = $heat_settings[$h] ?? [];
                $source_heat = $setting['flow_source_heat'] ?? null;
                
                // If this heat flows from a heat that's already processed, add it
                if ($source_heat && in_array($source_heat, $processed_for_order)) {
                    $heat_order[] = $h;
                    $processed_for_order[] = $h;
                }
            }
            $remaining_iterations--;
        }
        
        // Add any remaining heats that couldn't be sorted
        for ($h = 1; $h <= $heats_total; $h++) {
            if (!in_array($h, $processed_for_order)) {
                $heat_order[] = $h;
            }
        }
        ?>
        
        <div class="row" id="heat-buttons-container">
            <!-- Heat cards will be loaded via AJAX -->
            <div class="col-12 text-center py-5">
                <div class="spinner-border text-primary" role="status">
                    <span class="visually-hidden">Loading heats...</span>
                </div>
                <p class="mt-2 text-muted">Loading heat cards...</p>
            </div>
        </div>
     
    </div>

        <!-- Heat Flow Bracket Visualization -->
        <div class="card mb-4 shadow-sm">
            <div class="card-header text-white d-flex justify-content-between align-items-center p-2 bg-dark">
                <h5 class="mb-0">
                    <i class="fas fa-sitemap me-2"></i>Heat Flow Bracket
                </h5>
                <button type="button" class="btn btn-sm btn-light" id="toggleBracketParticipants" onclick="toggleBracketParticipants()">
                    <i class="fas fa-users me-1"></i>
                    <span id="bracketParticipantsToggleText">Show Participants</span>
                </button>
            </div>
            <div class="card-body p-4" style="background: linear-gradient(135deg, #596269 0%, #212529 100%); min-height: 400px;">
                <style>
                    .bracket-container {
                        position: relative;
                        padding: 20px;
                    }
                    .bracket-heat-card {
                        position: relative;
                        z-index: 2;
                        min-width: 400px;
                        max-width: 550px;
                          right: 0px;
                    }
                    .heat-connection-line {
                        position: absolute;
                        pointer-events: none;
                        z-index: 1;
                    }
                    .connection-path {
                        fill: none;
                        stroke: rgb(64 198 154);;
                        stroke-width: 3;
                        stroke-linecap: round;
                    }
                    .connection-arrow {
                        fill: rgb(64 198 154);;
                    }
                    .bracket-heat-card[data-heat-id]:hover {
                        right: -5px;
                        transition: right 0.2s;
                        box-shadow: 0 6px 12px rgba(0,0,0,0.4) !important;
                    }
                    .bracket-heat-card .btn:hover {
                        background-color: var(--bs-primary) !important;
                        color: white !important;
                    }
                    .bracket-participants-list {
                        display: none;
                        margin-top: 8px;
                        padding-top: 8px;
                        border-top: 1px solid #dee2e6;
                        max-height: 150px;
                        overflow-y: auto;
                    }
                    .bracket-participants-list.show {
                        display: block;
                    }
                    .bracket-participant-item {
                        display: flex;
                        align-items: center;
                        gap: 6px;
                        padding: 3px 0;
                        font-size: 0.75rem;
                    }
                    .bracket-participant-bib {
                        background: #ffc107;
                        color: #000;
                        font-weight: bold;
                        padding: 1px 4px;
                        border-radius: 3px;
                        min-width: 26px;
                        text-align: center;
                        font-size: 0.7rem;
                    }
                    .bracket-participant-flag {
                        font-size: 1rem;
                    }
                    .bracket-participant-name {
                        flex: 1;
                        white-space: nowrap;
                        overflow: hidden;
                        text-overflow: ellipsis;
                        font-size: 0.75rem;
                    }
                    .bracket-heat-card.active-heat {
    background: #2fb380 !important;
    border: 1px #00ff3a solid !important;
}
                </style>
                
                <div class="bracket-container" id="bracketContainer">
                    <?php
                    // Build bracket structure based on flow connections
                    $bracket_levels = [];
                    $processed_heats = [];
                    $heat_positions = []; // Track positions for drawing lines
                    
                    // Find starting heats (no source heat)
                    $starting_heats = [];
                    foreach ($heat_settings as $heat) {
                        $source_heats = [];
                        if (!empty($heat['flow_source_heat'])) {
                            $decoded = json_decode($heat['flow_source_heat'], true);
                            $source_heats = is_array($decoded) ? $decoded : [$heat['flow_source_heat']];
                        }
                        if (empty($source_heats)) {
                            $starting_heats[] = $heat;
                        }
                    }
                    
                    // Build levels
                    $bracket_levels[0] = $starting_heats;
                    $current_level = 0;
                    
                    while (!empty($bracket_levels[$current_level])) {
                        $next_level = [];
                        foreach ($bracket_levels[$current_level] as $heat) {
                            $processed_heats[] = $heat['heat_number'];
                        }
                        
                        // Find heats that flow from current level
                        foreach ($heat_settings as $potential_next) {
                            if (in_array($potential_next['heat_number'], $processed_heats)) continue;
                            
                            $source_heats = [];
                            if (!empty($potential_next['flow_source_heat'])) {
                                $decoded = json_decode($potential_next['flow_source_heat'], true);
                                $source_heats = is_array($decoded) ? $decoded : [$potential_next['flow_source_heat']];
                            }
                            
                            // Check if any source heat is in current level
                            $has_source_in_level = false;
                            foreach ($bracket_levels[$current_level] as $level_heat) {
                                if (in_array($level_heat['heat_number'], $source_heats)) {
                                    $has_source_in_level = true;
                                    break;
                                }
                            }
                            
                            if ($has_source_in_level && !in_array($potential_next, $next_level)) {
                                $next_level[] = $potential_next;
                            }
                        }
                        
                        if (!empty($next_level)) {
                            $bracket_levels[++$current_level] = $next_level;
                        } else {
                            break;
                        }
                    }
                    
                    // Build connections data for JavaScript
                    $connections = [];
                    foreach ($heat_settings as $heat) {
                        if (!empty($heat['flow_source_heat'])) {
                            $decoded = json_decode($heat['flow_source_heat'], true);
                            $source_heats = is_array($decoded) ? $decoded : [$heat['flow_source_heat']];
                            foreach ($source_heats as $source) {
                                $connections[] = [
                                    'from' => (int)$source,
                                    'to' => (int)$heat['heat_number']
                                ];
                            }
                        }
                    }
                    ?>
                    
                    <svg class="heat-connection-line" style="position: absolute; top: 0; left: 0; width: 100%; height: 100%; pointer-events: none;">
                        <defs>
                            <marker id="arrowhead" markerWidth="10" markerHeight="10" refX="9" refY="3" orient="auto">
                                <polygon points="0 0, 10 3, 0 6" class="connection-arrow" />
                            </marker>
                        </defs>
                    </svg>
                    
                    <div class="bracket-grid" style="display: flex; align-items: center; justify-content: center; flex-wrap: nowrap; overflow-x: auto; position: relative;">
                        <?php foreach ($bracket_levels as $level_idx => $level_heats): ?>
                            <div class="bracket-column" style="display: flex; flex-direction: column; gap: 20px; min-width: 200px;" data-level="<?= $level_idx ?>">
                                <div class="text-center mb-3">
                                    <span class="badge bg-white text-primary fw-bold px-3 py-2">
                                        <?= $level_idx === 0 ? 'QUALIFYING' : ($level_idx === count($bracket_levels) - 1 ? 'FINAL' : 'ROUND ' . ($level_idx + 1)) ?>
                                    </span>
                                </div>
                                
                                <?php foreach ($level_heats as $heat): ?>
                                    <div class="bracket-heat-card p-1 bg-primary-subtle border border-primary shadow-sm <?php if ($heat['is_active']): ?>active-heat<?php endif; ?>" 
                                         data-heat-id="<?= $heat['heat_number'] ?>"
                                         data-level="<?= $level_idx ?>"
                                         style="background: transparent;border-radius: 8px;position: relative;">
                                        <!-- Header Row with Config Buttons -->
                                                <div class="d-flex align-items-center justify-content-between mb-2">
                                                    <div class="d-flex align-items-center gap-2">
                                                        <span class="badge bg-primary fw-bold">HEAT <?= $heat['heat_number'] ?></span>
                                                        
                                                         <!-- Heat Name -->
                                                <?php if (!empty($heat['heat_name'])): ?>
                                                    <div class="fw-bold text-dark mb-0" style="font-size: 1rem;">
                                                        <i class="fas fa-fire me-1 text-warning"></i>
                                                        <?= htmlspecialchars($heat['heat_name']) ?>
                                                    </div>
                                                <?php endif; ?>
                                                    </div>
                                                    
                                                    <!-- Action Buttons -->
                                                    <div class="d-flex gap-1 flex-wrap">
                                                        <?php if ($heat['is_active']): ?>
                                                            <button type="button" 
                                                                    class="btn btn-sm btn-danger" 
                                                                    style="font-size: 0.7rem; padding: 2px 6px;"
                                                                    onclick="closeHeat(<?= $heat['heat_number'] ?>)"
                                                                    title="End/Close Heat">
                                                                <i class="fas fa-stop"></i>
                                                            </button>
                                                            <button type="button" 
                                                                    class="btn btn-sm btn-outline-primary" 
                                                                    style="font-size: 0.7rem; padding: 2px 6px;"
                                                                    onclick="changeActiveRun(<?= $heat['heat_number'] ?>, -1)"
                                                                    <?= $heat['active_run'] <= 1 ? 'disabled' : '' ?>
                                                                    title="Previous Run">
                                                                <i class="fas fa-chevron-left"></i>
                                                            </button>
                                                            <button type="button" 
                                                                    class="btn btn-sm btn-outline-primary" 
                                                                    style="font-size: 0.7rem; padding: 2px 6px;"
                                                                    onclick="changeActiveRun(<?= $heat['heat_number'] ?>, 1)"
                                                                    <?= $heat['active_run'] >= $heat['runs_count'] ? 'disabled' : '' ?>
                                                                    title="Next Run">
                                                                <i class="fas fa-chevron-right"></i>
                                                            </button>
                                                        <?php else: ?>
                                                            <button type="button" 
                                                                    class="btn btn-sm btn-success" 
                                                                    style="font-size: 0.7rem; padding: 2px 6px;"
                                                                    onclick="activateHeat(<?= $heat['heat_number'] ?>)"
                                                                    title="Activate Heat">
                                                                <i class="fas fa-play"></i>
                                                            </button>
                                                        <?php endif; ?>
                                                        <a href="heats_configure.php?event_id=<?= $selected_event_id ?>&heat=<?= $heat['heat_number'] ?>" 
                                                           class="btn btn-sm btn-outline-primary" 
                                                           style="font-size: 0.7rem; padding: 2px 6px;"
                                                           title="Edit Participants">
                                                            <i class="fas fa-edit"></i>
                                                        </a>
                                                        <button type="button" 
                                                                class="btn btn-sm btn-outline-secondary" 
                                                                style="font-size: 0.7rem; padding: 2px 6px;"
                                                                onclick="openHeatModal(<?= $heat['heat_number'] ?>)"
                                                                title="Configure Heat">
                                                            <i class="fas fa-cog"></i>
                                                        </button>
                                                        <button type="button" 
                                                                class="btn btn-sm btn-info" 
                                                                style="font-size: 0.7rem; padding: 2px 6px;"
                                                                onclick="location.href='heat_management_modal.php?heat=<?= $heat['heat_number'] ?>&event_id=<?= $selected_event_id ?>&standalone=1'"
                                                                title="Manage start gate">
                                                            <i class="fas fa-dashboard"></i>
                                                        </button>
                                                    </div>
                                                    
                                                </div>
                                        <!-- Main Container: Left info + Right participants -->
                                        <div class="d-flex">
                                            <!-- Left Side: Heat Info -->
                                            <div class="p-1" style="width: 140px;">
                                                <?php if ($heat['is_active']): ?>
                                                            <span class="badge bg-success">
                                                                <i class="fas fa-circle fa-fade"></i> LIVE
                                                            </span>
                                                            <span class="badge bg-info">
                                                                <i class="fas fa-play-circle me-1"></i>Run <?= $heat['active_run'] ?>/<?= $heat['runs_count'] ?>
                                                            </span>
                                                        <?php endif; ?>
                                                
                                               
                                                <!-- Time Display -->
                                                <?php if ($heat['time_start']): ?>
                                                    <div class="mb-1">
                                                        <div class="badge text-bg-light">
                                                           
                                                                <div><i class="fas fa-clock me-1 text-primary"></i>
                                                                <?= date('H:i', strtotime($heat['time_start'])) ?></div>
                                                                <?php if ($heat['estimate_time_per_participant'] > 0 && $heat['participant_count'] > 0): ?>
                                                                    <?php
                                                                    $total_seconds = $heat['estimate_time_per_participant'] * $heat['participant_count'];
                                                                    $total_minutes = ceil($total_seconds / 60);
                                                                    $start_datetime = new DateTime($heat['time_start']);
                                                                    $finish_datetime = clone $start_datetime;
                                                                    $finish_datetime->add(new DateInterval('PT' . $total_minutes . 'M'));
                                                                    ?>
                                                                    <div class="text-muted small">
                                                                        <i class="fas fa-hourglass-half me-1"></i>
                                                                        ~<?= $total_minutes ?>min
                                                                    </div>
                                                                    <div class="text-muted small">
                                                                        <i class="fas fa-flag-checkered me-1"></i>
                                                                        <?= $finish_datetime->format('H:i') ?>
                                                                    </div>
                                                                <?php endif; ?>
                                                           
                                                        </div>
                                                    </div>
                                                <?php endif; ?>
                                                
                                                <!-- Progress Tracking -->
                                                <?php if ($heat['participant_count'] > 0): ?>
                                                    <?php
                                                    // Get scoring progress for this heat
                                                    $progress_stmt = $pdo->prepare("
                                                        SELECT 
                                                            COUNT(DISTINCT ep.participant_id) as total_participants,
                                                            COUNT(DISTINCT CASE WHEN s.id IS NOT NULL THEN ep.participant_id END) as participants_with_scores,
                                                            COUNT(DISTINCT CASE WHEN s.is_approved = 1 THEN ep.participant_id END) as approved_participants
                                                        FROM event_participants ep
                                                        LEFT JOIN runs r ON r.event_participant_id = ep.id AND r.run_number = ?
                                                        LEFT JOIN scores s ON s.run_id = r.id
                                                        WHERE ep.event_id = ? AND ep.heat_number = ?
                                                    ");
                                                    $progress_stmt->execute([$heat['active_run'] ?? 1, $selected_event_id, $heat['heat_number']]);
                                                    $progress = $progress_stmt->fetch(PDO::FETCH_ASSOC);
                                                    
                                                    $total = $progress['total_participants'];
                                                    $scored = $progress['participants_with_scores'];
                                                    $approved = $progress['approved_participants'];
                                                    $progress_percentage = $total > 0 ? round(($scored / $total) * 100) : 0;
                                                    $approval_percentage = $total > 0 ? round(($approved / $total) * 100) : 0;
                                                    $progress_variant = $progress_percentage >= 100 ? 'success' : ($progress_percentage >= 50 ? 'warning' : 'primary');
                                                    ?>
                                                    <?php if ($scored > 0): ?>
                                                    <div class="border-0 shadow-none card border-secondary mb-2">
                                                        <div class="border-0 shadow-none card-header bg-secondary bg-opacity-10 py-1">
                                                            <i class="fas fa-chart-bar me-1"></i>
                                                            <span class="fw-bold small">Progress: <?= $scored ?>/<?= $total ?></span>
                                                            <span class="badge bg-<?= $progress_variant ?> ms-2"><?= $progress_percentage ?>%</span>
                                                        </div>
                                                        <div class="border-0 shadow-none card-body py-2">
                                                            <div class="progress mb-2" style="height: 15px;">
                                                                <div class="progress-bar bg-<?= $progress_variant ?>" role="progressbar" 
                                                                     style="width: <?= $progress_percentage ?>%" 
                                                                     aria-valuenow="<?= $progress_percentage ?>" 
                                                                     aria-valuemin="0" aria-valuemax="100">
                                                                    <?= $progress_percentage ?>%
                                                                </div>
                                                            </div>
                                                            <?php if ($scored > 0): ?>
                                                                <div class="d-flex align-items-center">
                                                                    <i class="fas fa-trophy me-1"></i>
                                                                    <span class="me-2 small">Scoring: <?= $scored ?>/<?= $total ?></span>
                                                                    <span class="badge bg-info"><?= $approval_percentage ?>%</span>
                                                                </div>
                                                            <?php endif; ?>
                                                        </div>
                                                    </div>
                                                    <?php endif; ?>
                                                <?php endif; ?>
                                                
                                                
                                                
                                                <!-- Categories -->
                                                <div>
                                                    <?php if (count($heat['categories']) <= 2): ?>
                                                        <span class="badge text-bg-secondary small"><i class="fas fa-tags me-1"></i><?= implode('</span> <span class="badge text-bg-secondary small"><i class="fas fa-tags me-1"></i>', $heat['categories']) ?></span>
                                                    <?php else: ?>
                                                        <span class="badge text-bg-secondary small">
                                                            <i class="fas fa-tags me-1"></i><?= count($heat['categories']) ?> Categories
                                                        </span>
                                                    <?php endif; ?>
                                                </div>

                                                
                                            </div>
                                            
                                            <!-- Right Side: Participants List (Always Visible) -->
                                            <div class="border-start p-1 w-100" style="min-width: 180px;">
                                                <!-- Flow/Assignment Type -->
                                                <div class="mb-1 small">
                                                    <?php if ($heat['flow_type'] !== 'none'): ?>
                                                        <?php if ($heat['flow_type'] === 'promotion'): ?>
                                                            <span class="badge text-bg-light bg-warning-subtle text-warning border border-warning-subtle">
                                                                <i class="fas fa-arrow-up me-1"></i>Auto Promotion
                                                            </span>
                                                        <?php elseif ($heat['flow_type'] === 'qualifying'): ?>
                                                            <span class="badge bg-info-subtle text-info border border-info-subtle">
                                                                <i class="fas fa-filter me-1"></i>Auto Qualifying
                                                            </span>
                                                        <?php endif; ?>
                                                        <div class="small text-muted mt-1">
                                                            <?php 
                                                            // Parse source heats (could be JSON array or single value)
                                                            $source_heats = [];
                                                            if (!empty($heat['flow_source_heat'])) {
                                                                $decoded = json_decode($heat['flow_source_heat'], true);
                                                                $source_heats = is_array($decoded) ? $decoded : [$heat['flow_source_heat']];
                                                            }
                                                            
                                                            $flow_info = '';
                                                            if (!empty($heat['flow_position_range'])) {
                                                                $flow_info = 'Positions ' . htmlspecialchars($heat['flow_position_range']);
                                                            } else {
                                                                $flow_info = 'Top ' . $heat['flow_participants_per_category'];
                                                            }
                                                            ?>
                                                            From Heat<?= count($source_heats) > 1 ? 's' : '' ?> <?= implode(', ', $source_heats) ?> • <?= $flow_info ?>
                                                        </div>
                                                    <?php else: ?>
                                                        <?php
                                                        $has_incoming_flow = false;
                                                        if (!empty($heat_settings)) {
                                                            foreach ($heat_settings as $other_heat) {
                                                                // Check if current heat is in the source heats (handle JSON array or single value)
                                                                $other_source_heats = [];
                                                                if (!empty($other_heat['flow_source_heat'])) {
                                                                    $decoded = json_decode($other_heat['flow_source_heat'], true);
                                                                    $other_source_heats = is_array($decoded) ? $decoded : [$other_heat['flow_source_heat']];
                                                                }
                                                                if (in_array($heat['heat_number'], $other_source_heats)) {
                                                                    $has_incoming_flow = true;
                                                                    break;
                                                                }
                                                            }
                                                        }
                                                        ?>
                                                        <?php if (!$has_incoming_flow): ?>
                                                            <span class="badge bg-success-subtle text-success border border-success-subtle">
                                                                <i class="fas fa-play me-1"></i>Starting Heat
                                                            </span>
                                                        <?php else: ?>
                                                            <span class="badge bg-warning-subtle text-warning border border-warning-subtle">
                                                                <i class="fas fa-hand-paper me-1"></i>Manual Assignment
                                                            </span>
                                                        <?php endif; ?>
                                                    <?php endif; ?>
                                                </div>
                                                <div style="max-height: 250px; overflow-y: auto;">
                                                    <?php
                                                    $heat_num = $heat['heat_number'];
                                                    $participants = $heat_participants[$heat_num] ?? [];
                                                    if (!empty($participants)):
                                                        $displayParticipants = array_slice($participants, 0, 4);
                                                        $remainingCount = count($participants) - count($displayParticipants);
                                                    ?>
                                                        <?php foreach ($displayParticipants as $participant): ?>
                                                            <div class="d-flex align-items-center gap-1 mb-1 p-1 bg-light rounded" style="font-size: 0.75rem;">
                                                                <span class="badge bg-white text-dark fw-bold" style="min-width: 26px; font-size: 0.7rem;">
                                                                    <?= $participant['bib_number'] ?>
                                                                </span>
                                                                <?php if (!empty($participant['country'])): ?>
                                                                    <?php
                                                                    // Convert country code to flag emoji
                                                                    $country = strtoupper($participant['country']);
                                                                    if (strlen($country) === 3) {
                                                                        // Map common 3-letter codes to 2-letter codes
                                                                        $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);
                                                                    }
                                                                    $flag = strlen($country) === 2 ? 
                                                                        mb_chr(127462 + ord($country[0]) - 65) . mb_chr(127462 + ord($country[1]) - 65) : 
                                                                        '🏳️';
                                                                    ?>
                                                                    <span class="country-code" style="font-size: 1rem;"><?= $flag ?></span>
                                                                <?php else: ?>
                                                                    <span class="country-code" style="font-size: 1rem;">🏳️</span>
                                                                <?php endif; ?>
                                                                <span class="text-truncate fw-bold" style="flex: 1;">
                                                                    <?= htmlspecialchars($participant['last_name']) ?>, <?= htmlspecialchars($participant['first_name']) ?>
                                                                </span>
                                                            </div>
                                                        <?php endforeach; ?>
                                                        <?php if ($remainingCount > 0): ?>
                                                            <div class="text-muted small text-center p-1">
                                                                <i class="fas fa-plus-circle me-1"></i>+<?= $remainingCount ?> more
                                                            </div>
                                                        <?php endif; ?>
                                                    <?php else: ?>
                                                        <div class="text-muted small text-center p-2">
                                                            <i class="fas fa-info-circle me-1"></i>No participants
                                                        </div>
                                                    <?php endif; ?>
                                                </div>
                                            </div>
                                        </div>
                                        
                                        
                                    </div>
                                <?php endforeach; ?>
                            </div>
                            
                            <?php if ($level_idx < count($bracket_levels) - 1): ?>
                                <div class="bracket-connector ps-2 pe-5" style="display: flex; align-items: center; color: white; z-index: 0;">
                                    <i class="fas fa-chevron-right fa-2x opacity-25"></i>
                                </div>
                            <?php endif; ?>
                        <?php endforeach; ?>
                    </div>
                    
                    <script>
                    document.addEventListener('DOMContentLoaded', function() {
                        const connections = <?= json_encode($connections) ?>;
                        const svg = document.querySelector('.heat-connection-line');
                        const container = document.getElementById('bracketContainer');
                        
                        function drawConnections() {
                            // Clear existing paths
                            const existingPaths = svg.querySelectorAll('path, line');
                            existingPaths.forEach(p => p.remove());
                            
                            // Group connections by destination to draw bracket-style
                            const connsByDestination = {};
                            connections.forEach(conn => {
                                if (!connsByDestination[conn.to]) {
                                    connsByDestination[conn.to] = [];
                                }
                                connsByDestination[conn.to].push(conn.from);
                            });
                            
                            // Draw bracket-style connections
                            Object.keys(connsByDestination).forEach(toHeat => {
                                const fromHeats = connsByDestination[toHeat];
                                const toCard = document.querySelector('[data-heat-id="' + toHeat + '"]');
                                if (!toCard) return;
                                
                                const containerRect = container.getBoundingClientRect();
                                const toRect = toCard.getBoundingClientRect();
                                const x2 = toRect.left - containerRect.left;
                                const y2 = toRect.top + toRect.height / 2 - containerRect.top;
                                
                                if (fromHeats.length === 1) {
                                    // Single connection - straight line
                                    const fromCard = document.querySelector('[data-heat-id="' + fromHeats[0] + '"]');
                                    if (!fromCard) return;
                                    
                                    const fromRect = fromCard.getBoundingClientRect();
                                    const x1 = fromRect.right - containerRect.left;
                                    const y1 = fromRect.top + fromRect.height / 2 - containerRect.top;
                                    
                                    const line = document.createElementNS('http://www.w3.org/2000/svg', 'line');
                                    line.setAttribute('class', 'connection-path');
                                    line.setAttribute('x1', x1);
                                    line.setAttribute('y1', y1);
                                    line.setAttribute('x2', x2);
                                    line.setAttribute('y2', y2);
                                    line.setAttribute('marker-end', 'url(#arrowhead)');
                                    svg.appendChild(line);
                                } else {
                                    // Multiple connections - bracket style
                                    let minY = Infinity, maxY = -Infinity;
                                    const fromPositions = [];
                                    
                                    fromHeats.forEach(fromHeat => {
                                        const fromCard = document.querySelector('[data-heat-id="' + fromHeat + '"]');
                                        if (!fromCard) return;
                                        
                                        const fromRect = fromCard.getBoundingClientRect();
                                        const x1 = fromRect.right - containerRect.left;
                                        const y1 = fromRect.top + fromRect.height / 2 - containerRect.top;
                                        
                                        fromPositions.push({x: x1, y: y1});
                                        minY = Math.min(minY, y1);
                                        maxY = Math.max(maxY, y1);
                                    });
                                    
                                    // Calculate the midpoint for the vertical connector
                                    const midY = (minY + maxY) / 2;
                                    const junctionX = x2 - 30; // Junction point 30px before destination
                                    
                                    // Draw horizontal lines from each source to junction
                                    fromPositions.forEach(pos => {
                                        const line1 = document.createElementNS('http://www.w3.org/2000/svg', 'line');
                                        line1.setAttribute('class', 'connection-path');
                                        line1.setAttribute('x1', pos.x);
                                        line1.setAttribute('y1', pos.y);
                                        line1.setAttribute('x2', junctionX);
                                        line1.setAttribute('y2', pos.y);
                                        svg.appendChild(line1);
                                    });
                                    
                                    // Draw vertical connector line
                                    const verticalLine = document.createElementNS('http://www.w3.org/2000/svg', 'line');
                                    verticalLine.setAttribute('class', 'connection-path');
                                    verticalLine.setAttribute('x1', junctionX);
                                    verticalLine.setAttribute('y1', minY);
                                    verticalLine.setAttribute('x2', junctionX);
                                    verticalLine.setAttribute('y2', maxY);
                                    svg.appendChild(verticalLine);
                                    
                                    // Draw final horizontal line to destination with arrow
                                    const finalLine = document.createElementNS('http://www.w3.org/2000/svg', 'line');
                                    finalLine.setAttribute('class', 'connection-path');
                                    finalLine.setAttribute('x1', junctionX);
                                    finalLine.setAttribute('y1', midY);
                                    finalLine.setAttribute('x2', x2);
                                    finalLine.setAttribute('y2', y2);
                                    finalLine.setAttribute('marker-end', 'url(#arrowhead)');
                                    svg.appendChild(finalLine);
                                }
                            });
                        }
                        
                        // Draw connections after DOM is ready
                        setTimeout(drawConnections, 100);
                        
                        // Redraw on window resize
                        let resizeTimer;
                        window.addEventListener('resize', function() {
                            clearTimeout(resizeTimer);
                            resizeTimer = setTimeout(drawConnections, 250);
                        });
                    });
                    
                    function toggleBracketParticipants() {
                        const participantLists = document.querySelectorAll('.bracket-participants-list');
                        const toggleText = document.getElementById('bracketParticipantsToggleText');
                        const isShowing = participantLists[0]?.classList.contains('show');
                        
                        participantLists.forEach(list => {
                            if (isShowing) {
                                list.classList.remove('show');
                            } else {
                                list.classList.add('show');
                            }
                        });
                        
                        if (isShowing) {
                            toggleText.textContent = 'Show Participants';
                        } else {
                            toggleText.textContent = 'Hide Participants';
                        }
                    }
                    </script>
                    
                    <?php if (empty($bracket_levels) || empty($bracket_levels[0])): ?>
                        <div class="text-center text-white py-5">
                            <i class="fas fa-info-circle fa-3x mb-3"></i>
                            <p class="lead">No heat flow configuration detected</p>
                            <p>Configure heat flow settings below to see the bracket visualization</p>
                        </div>
                    <?php endif; ?>
                </div>
            </div>
        </div>
    
       
        

        <!-- Heat Flow Visualization -->
        <?php if (!empty($heat_settings) && $heats_total > 0): ?>
            <div class="border-0 card card-body d-flex flex-row flex-wrap mb-4 overflow-auto shadow-none">
                
                
                <?php
                // Build flow chains based on actual connections
                $processed_heats = [];
                $flow_chains = [];
                
                for ($h = 1; $h <= $heats_total; $h++) {
                    if (in_array($h, $processed_heats)) continue;
                    
                    $current_chain = [];
                    $heat_to_process = $h;
                    
                    // Start a new chain with current heat
                    while ($heat_to_process && !in_array($heat_to_process, $processed_heats)) {
                        $setting = $heat_settings[$heat_to_process] ?? [];
                        
                        // Get category names for display
                        $heat_categories = $setting['categories'] ?? [];
                        $category_names = [];
                        if (empty($heat_categories)) {
                            $category_names = ['All Categories'];
                        } else {
                            foreach ($event_categories as $cat) {
                                if (in_array($cat['id'], $heat_categories)) {
                                    $category_names[] = $cat['category_name'];
                                }
                            }
                        }
                        
                        $current_chain[] = [
                            'heat_number' => $heat_to_process,
                            'heat_name' => $setting['heat_name'] ?? '',
                            'flow_type' => $setting['flow_type'] ?? 'none',
                            'flow_participants_per_category' => $setting['flow_participants_per_category'] ?? 0,
                            'flow_position_range' => $setting['flow_position_range'] ?? null,
                            'flow_source_heat' => $setting['flow_source_heat'] ?? null,
                            'is_active' => $setting['is_active'] ?? false,
                            'categories' => $category_names,
                            'participant_count' => $heat_participant_counts[$heat_to_process] ?? 0,
                            'time_start' => $setting['time_start'] ?? '',
                            'estimate_time_per_participant' => $setting['estimate_time_per_participant'] ?? 0
                        ];
                        
                        $processed_heats[] = $heat_to_process;
                        
                        // Find next heat that flows from this one
                        $next_heat = null;
                        for ($next = $heat_to_process + 1; $next <= $heats_total; $next++) {
                            $next_setting = $heat_settings[$next] ?? [];
                            if (($next_setting['flow_source_heat'] ?? null) == $heat_to_process) {
                                $next_heat = $next;
                                break;
                            }
                        }
                        
                        $heat_to_process = $next_heat;
                    }
                    
                    if (!empty($current_chain)) {
                        $flow_chains[] = $current_chain;
                    }
                }
                ?>
                
                <!-- Flow Statistics -->
                <div class="mt-3 pt-3 border-top" style="display: none;">
                    <div class="row">
                        <div class="col-md-3">
                            <div class="summary-stat">
                                <i class="fas fa-fire text-warning me-2"></i>
                                <strong><?= $heats_total ?></strong> Total Heats
                            </div>
                        </div>
                        <div class="col-md-3">
                            <div class="summary-stat">
                                <i class="fas fa-stream text-info me-2"></i>
                                <strong><?= count($flow_chains) ?></strong> Flow Chain<?= count($flow_chains) > 1 ? 's' : '' ?>
                            </div>
                        </div>
                        <div class="col-md-3">
                            <div class="summary-stat">
                                <?php 
                                $auto_flow_count = 0;
                                if (!empty($heat_settings)) {
                                    foreach ($heat_settings as $setting) {
                                        if (($setting['flow_type'] ?? 'none') !== 'none') {
                                            $auto_flow_count++;
                                        }
                                    }
                                }
                                ?>
                                <i class="fas fa-route text-success me-2"></i>
                                <strong><?= $auto_flow_count ?></strong> Auto Flow
                            </div>
                        </div>
                        <div class="col-md-3">
                            <div class="summary-stat">
                                <?php 
                                $starting_count = 0;
                                if (!empty($heat_settings)) {
                                    foreach ($heat_settings as $h_num => $setting) {
                                        if (($setting['flow_type'] ?? 'none') === 'none') {
                                            // Check if any other heat flows from this one
                                            $has_outgoing = false;
                                            foreach ($heat_settings as $other_setting) {
                                                if (($other_setting['flow_source_heat'] ?? null) == $h_num) {
                                                    $has_outgoing = true;
                                                    break;
                                                }
                                            }
                                            if (!$has_outgoing) {
                                                $starting_count++;
                                            }
                                        }
                                    }
                                }
                                ?>
                                <i class="fas fa-play text-primary me-2"></i>
                                <strong><?= $starting_count ?></strong> Starting
                            </div>
                        </div>
                    </div>
                    
                    <!-- Flow Examples -->
                    <?php if (count($flow_chains) > 1): ?>
                        <div class="mt-3" style="display: none;">
                            <h6 class="text-muted mb-2">
                                <i class="fas fa-sitemap me-1"></i>Flow Structure:
                            </h6>
                            <?php foreach ($flow_chains as $chain_idx => $chain): ?>
                                <div class="flow-example mb-1">
                                    <small class="text-info">
                                        <strong>Chain <?= $chain_idx + 1 ?>:</strong>
                                         <?php foreach ($chain as $idx => $heat): ?>
                                            <?= !empty($heat['heat_name']) ? $heat['heat_name'] : "Heat {$heat['heat_number']}" ?>
                                            <span class="text-muted">(<?= implode(', ', array_slice($heat['categories'], 0, 2)) ?><?= count($heat['categories']) > 2 ? '...' : '' ?>)</span>
                                            <?php if ($idx < count($chain) - 1): ?>
                                                <?php 
                                                $next_heat = $chain[$idx + 1];
                                                $has_flow = ($next_heat['flow_source_heat'] ?? null) == $heat['heat_number'];
                                                ?>
                                                <?= $has_flow ? ' → ' : ' | ' ?>
                                            <?php endif; ?>
                                        <?php endforeach; ?>
                                    </small>
                                </div>
                            <?php endforeach; ?>
                        </div>
                    <?php endif; ?>
                </div>
            </div>
        <?php endif; ?>

  
    <!-- Heat Configuration Modals -->
    <?php foreach ($heat_order as $h): ?>
        <?php 
        $setting = $heat_settings[$h] ?? [
            'heat_name' => '', 
            'scoring_type' => 'Points',
            'runs_count' => 1,
            'runs_scoring_method' => 'best_from_all',
            'time_start' => '',
            'estimate_time_per_participant' => 0,
            'categories' => [],
            'flow_type' => 'none',
            'flow_source_heat' => null,
            'flow_participants_per_category' => 0,
            'flow_position_range' => null,
            'is_active' => 0,
            'active_run' => 1,
            'status' => 'pending',
            'format_name' => $event_data['format_name'] ?? '',
            'discipline' => $event_data['discipline'] ?? '',
            'difficulty_level' => '',
            'course_length' => 0,
            'time_limit' => 0,
            'weather_dependent' => 0,
            'format_description' => '',
            'scoring_method' => 'standard',
            'required_figures' => [],
            'judges_required' => 5,
            'scale_min' => $event_data['scale_min'] ?? 0,
            'scale_max' => $event_data['scale_max'] ?? 100,
            'precision_decimal' => $event_data['precision_decimal'] ?? 0
        ];
        ?>
        
        <div class="modal fade" id="heatModal<?= $h ?>" tabindex="-1" aria-labelledby="heatModalLabel<?= $h ?>" aria-hidden="true">
            <div class="modal-dialog modal-xl">
                <div class="modal-content">
                    <div class="modal-header">
                        <h5 class="modal-title" id="heatModalLabel<?= $h ?>">
                            <i class="fas fa-fire me-2 text-warning"></i>
                            Configure Heat <?= $h ?>
                            <?php if ($setting['is_active']): ?>
                                <span class="badge text-bg-success ms-2">ACTIVE</span>
                            <?php endif; ?>
                        </h5>
                        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                    </div>
                    
                    <form method="post" onsubmit="return validateHeatForm(<?= $h ?>)">
                        <input type="hidden" name="event_id" value="<?= $selected_event_id ?>">
                        <input type="hidden" name="save_settings" value="1">
                        <input type="hidden" name="single_heat" value="<?= $h ?>">
                        
                        <div class="modal-body">
                            <!-- Heat Activation Status -->
                            <?php if ($setting['is_active']): ?>
                                <div class="alert alert-success border-0 mb-4">
                                    <div class="d-flex align-items-center">
                                        <i class="fas fa-fire text-success fs-4 me-3"></i>
                                        <div>
                                            <h6 class="mb-1">This Heat is Currently Active</h6>
                                            <small class="text-muted">All scoring activity is directed to this heat</small>
                                        </div>
                                    </div>
                                </div>
                            <?php endif; ?>
                            
                            <!-- Tabbed Interface -->
                            <ul class="nav nav-tabs mb-4" id="heatConfigTabs<?= $h ?>" role="tablist">
                                <li class="nav-item" role="presentation">
                                    <button class="nav-link active" id="basic-tab-<?= $h ?>" data-bs-toggle="tab" 
                                            data-bs-target="#basic-<?= $h ?>" type="button" role="tab">
                                        <i class="fas fa-info-circle me-2"></i>Basic Settings
                                    </button>
                                </li>
                                <li class="nav-item" role="presentation">
                                    <button class="nav-link" id="timing-tab-<?= $h ?>" data-bs-toggle="tab" 
                                            data-bs-target="#timing-<?= $h ?>" type="button" role="tab">
                                        <i class="fas fa-clock me-2"></i>Timing & Runs
                                    </button>
                                </li>
                                <li class="nav-item" role="presentation">
                                    <button class="nav-link" id="format-tab-<?= $h ?>" data-bs-toggle="tab" 
                                            data-bs-target="#format-<?= $h ?>" type="button" role="tab">
                                        <i class="fas fa-clipboard-list me-2"></i>Format
                                    </button>
                                </li>
                                <li class="nav-item" role="presentation">
                                    <button class="nav-link" id="flow-tab-<?= $h ?>" data-bs-toggle="tab" 
                                            data-bs-target="#flow-<?= $h ?>" type="button" role="tab">
                                        <i class="fas fa-sitemap me-2"></i>Flow
                                    </button>
                                </li>
                                <li class="nav-item" role="presentation">
                                    <button class="nav-link" id="activation-tab-<?= $h ?>" data-bs-toggle="tab" 
                                            data-bs-target="#activation-<?= $h ?>" type="button" role="tab">
                                        <i class="fas fa-power-off me-2"></i>Activation
                                    </button>
                                </li>
                                <li class="nav-item" role="presentation">
                                    <button class="nav-link" id="scoring-layout-tab-<?= $h ?>" data-bs-toggle="tab" 
                                            data-bs-target="#scoring-layout-<?= $h ?>" type="button" role="tab">
                                        <i class="fas fa-layout me-2"></i>Score Input Layout
                                    </button>
                                </li>
                            </ul>
                            
                            <!-- Tab Content -->
                            <div class="tab-content" id="heatConfigTabContent<?= $h ?>">
                                
                                <!-- Basic Settings Tab -->
                                <div class="tab-pane fade show active" id="basic-<?= $h ?>" role="tabpanel">
                                    <div class="row">
                                        <div class="col-md-6">
                                            <div class="mb-3">
                                                <label class="form-label fw-semibold">Heat Name</label>
                                                <input type="text" class="form-control" 
                                                       name="heat_name[<?= $h ?>]" 
                                                       value="<?= htmlspecialchars($setting['heat_name'] ?? '') ?>"
                                                       placeholder="Enter descriptive heat name">
                                                <div class="form-text">Optional: Give this heat a descriptive name</div>
                                            </div>
                                        </div>
                                        
                                        <div class="col-md-6">
                                            <div class="mb-3">
                                                <label class="form-label fw-semibold">Scoring Type</label>
                                                <select class="form-select" name="scoring_type[<?= $h ?>]">
                                                    <option value="Points" <?= $setting['scoring_type'] == 'Points' ? 'selected' : '' ?>>Points Based</option>
                                                    <option value="Time" <?= $setting['scoring_type'] == 'Time' ? 'selected' : '' ?>>Time Based</option>
                                                </select>
                                                <div class="form-text">How this heat will be scored</div>
                                            </div>
                                        </div>
                                    </div>
                                    
                                    <div class="mb-4">
                                        <label class="form-label fw-semibold">Categories</label>
                                        <?php if (empty($event_categories)): ?>
                                            <div class="alert alert-warning">
                                                <i class="fas fa-exclamation-triangle me-2"></i>
                                                No categories defined for this event. 
                                                <a href="event_categories.php?event_id=<?= $selected_event_id ?>" class="alert-link">Add categories first</a>
                                            </div>
                                        <?php else: ?>
                                            <div class="border-0 shadow-none card">
                                                <div class="border-0 shadow-none card-header py-2">
                                                    <div class="form-check">
                                                        <input class="form-check-input" type="checkbox" 
                                                               id="all_categories_modal_<?= $h ?>"
                                                               <?= empty($setting['categories']) ? 'checked' : '' ?>
                                                               onchange="toggleAllCategoriesModal(<?= $h ?>)">
                                                        <label class="form-check-label fw-semibold" for="all_categories_modal_<?= $h ?>">
                                                            All Categories
                                                        </label>
                                                    </div>
                                                </div>
                                                <div class="border-0 shadow-none card-body" style="max-height: 200px; overflow-y: auto;">
                                                    <div class="row">
                                                        <?php foreach ($event_categories as $category): ?>
                                                            <div class="col-md-6">
                                                                <div class="form-check">
                                                                    <input class="form-check-input category-checkbox" type="checkbox" 
                                                                           name="categories[<?= $h ?>][]" 
                                                                           value="<?= $category['id'] ?>"
                                                                           id="cat_modal_<?= $h ?>_<?= $category['id'] ?>"
                                                                           data-heat="<?= $h ?>"
                                                                           <?= in_array($category['id'], $setting['categories']) ? 'checked' : '' ?>
                                                                           <?= empty($setting['categories']) ? 'disabled' : '' ?>
                                                                           onchange="updateCategorySelectionModal(<?= $h ?>)">
                                                                    <label class="form-check-label" for="cat_modal_<?= $h ?>_<?= $category['id'] ?>">
                                                                        <?= htmlspecialchars($category['category_name']) ?>
                                                                    </label>
                                                                </div>
                                                            </div>
                                                        <?php endforeach; ?>
                                                    </div>
                                                </div>
                                            </div>
                                        <?php endif; ?>
                                    </div>
                                </div>
                                
                                <!-- Timing & Runs Tab -->
                                <div class="tab-pane fade" id="timing-<?= $h ?>" role="tabpanel">
                                    <div class="row">
                                        <div class="col-md-6">
                                            <div class="mb-3">
                                                <label class="form-label fw-semibold">Start Time</label>
                                                <input type="time" class="form-control" 
                                                       name="time_start[<?= $h ?>]" 
                                                       value="<?= htmlspecialchars($setting['time_start'] ?? '') ?>"
                                                       onchange="calculateEstimatedFinishModal(<?= $h ?>)">
                                                <div class="form-text">When this heat is scheduled to begin</div>
                                            </div>
                                        </div>
                                        
                                        <div class="col-md-6">
                                            <div class="mb-3">
                                                <label class="form-label fw-semibold">Time per Participant</label>
                                                <div class="input-group">
                                                    <input type="number" class="form-control" 
                                                           name="estimate_time_per_participant[<?= $h ?>]" 
                                                           value="<?= $setting['estimate_time_per_participant'] ?>"
                                                           min="0" step="5"
                                                           onchange="calculateEstimatedFinishModal(<?= $h ?>)">
                                                    <span class="input-group-text">seconds</span>
                                                </div>
                                                <div class="form-text">Estimated time allocation per participant</div>
                                            </div>
                                        </div>
                                    </div>
                                    
                                    <div class="row">
                                        <div class="col-md-6">
                                            <div class="mb-3">
                                                <label class="form-label fw-semibold">Number of Runs</label>
                                                <select class="form-select" name="runs_count[<?= $h ?>]" 
                                                        onchange="updateRunOptionsModal(<?= $h ?>)">
                                                    <?php for ($r = 1; $r <= 5; $r++): ?>
                                                        <option value="<?= $r ?>" <?= $setting['runs_count'] == $r ? 'selected' : '' ?>>
                                                            <?= $r ?> Run<?= $r > 1 ? 's' : '' ?>
                                                        </option>
                                                    <?php endfor; ?>
                                                </select>
                                                <div class="form-text">How many runs each participant gets</div>
                                            </div>
                                        </div>
                                        
                                        <div class="col-md-6">
                                            <div class="mb-3">
                                                <label class="form-label fw-semibold">Scoring Method</label>
                                                <select class="form-select" name="runs_scoring_method[<?= $h ?>]" 
                                                        id="runs_scoring_modal_<?= $h ?>"
                                                        onchange="updateScoringExplanationModal(<?= $h ?>)">
                                                    <!-- Options populated by JavaScript -->
                                                </select>
                                                <div class="form-text">
                                                    <span id="scoring_explanation_modal_<?= $h ?>">How to calculate final score from multiple runs</span>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                    
                                    <!-- Estimated Finish -->
                                    <div id="estimated_finish_modal_<?= $h ?>" class="alert alert-light border d-none">
                                        <i class="fas fa-clock text-primary me-2"></i>
                                        <strong>Estimated Finish:</strong>
                                        <span id="finish_time_modal_<?= $h ?>"></span>
                                    </div>
                                </div>
                                
                                <!-- Format Settings Tab -->
                                <div class="tab-pane fade" id="format-<?= $h ?>" role="tabpanel">
                                    <div class="row">
                                        <div class="col-lg-6">
                                            <h6 class="text-muted mb-3">Competition Format</h6>
                                            
                                            <div class="mb-3">
                                                <label class="form-label fw-semibold">Format Name</label>
                                                <input type="text" class="form-control" 
                                                       name="format_name[<?= $h ?>]" 
                                                       value="<?= htmlspecialchars($setting['format_name'] ?? '') ?>"
                                                       placeholder="e.g., Street Style, Park Competition">
                                                <div class="form-text">Override event format name for this heat</div>
                                            </div>
                                            
                                            <div class="mb-3">
                                                <label class="form-label fw-semibold">Discipline</label>
                                                <select class="form-select" name="discipline[<?= $h ?>]">
                                                    <option value="">-- Use Event Default --</option>
                                                    <option value="freestyle_scooter" <?= $setting['discipline'] == 'freestyle_scooter' ? 'selected' : '' ?>>Freestyle Scooter</option>
                                                    <option value="street_scooter" <?= $setting['discipline'] == 'street_scooter' ? 'selected' : '' ?>>Street Scooter</option>
                                                    <option value="park_scooter" <?= $setting['discipline'] == 'park_scooter' ? 'selected' : '' ?>>Park Scooter</option>
                                                    <option value="freestyle_skiing" <?= $setting['discipline'] == 'freestyle_skiing' ? 'selected' : '' ?>>Freestyle Skiing</option>
                                                    <option value="alpine_skiing" <?= $setting['discipline'] == 'alpine_skiing' ? 'selected' : '' ?>>Alpine Skiing</option>
                                                    <option value="snowboard_freestyle" <?= $setting['discipline'] == 'snowboard_freestyle' ? 'selected' : '' ?>>Snowboard Freestyle</option>
                                                    <option value="skateboard_street" <?= $setting['discipline'] == 'skateboard_street' ? 'selected' : '' ?>>Skateboard Street</option>
                                                    <option value="skateboard_park" <?= $setting['discipline'] == 'skateboard_park' ? 'selected' : '' ?>>Skateboard Park</option>
                                                    <option value="bmx_freestyle" <?= $setting['discipline'] == 'bmx_freestyle' ? 'selected' : '' ?>>BMX Freestyle</option>
                                                    <option value="breaking" <?= $setting['discipline'] == 'breaking' ? 'selected' : '' ?>>Breaking</option>
                                                    <option value="parkour" <?= $setting['discipline'] == 'parkour' ? 'selected' : '' ?>>Parkour</option>
                                                </select>
                                            </div>
                                            
                                            <div class="mb-3">
                                                <label class="form-label fw-semibold">Difficulty Level</label>
                                                <select class="form-select" name="difficulty_level[<?= $h ?>]">
                                                    <option value="">-- No Specific Level --</option>
                                                    <option value="beginner" <?= $setting['difficulty_level'] == 'beginner' ? 'selected' : '' ?>>Beginner</option>
                                                    <option value="intermediate" <?= $setting['difficulty_level'] == 'intermediate' ? 'selected' : '' ?>>Intermediate</option>
                                                    <option value="advanced" <?= $setting['difficulty_level'] == 'advanced' ? 'selected' : '' ?>>Advanced</option>
                                                    <option value="professional" <?= $setting['difficulty_level'] == 'professional' ? 'selected' : '' ?>>Professional</option>
                                                    <option value="elite" <?= $setting['difficulty_level'] == 'elite' ? 'selected' : '' ?>>Elite</option>
                                                </select>
                                            </div>
                                            
                                            <div class="mb-3">
                                                <label class="form-label fw-semibold">Scoring Method</label>
                                                <select class="form-select" name="scoring_method[<?= $h ?>]">
                                                    <option value="standard" <?= $setting['scoring_method'] == 'standard' ? 'selected' : '' ?>>Standard Scoring</option>
                                                    <option value="comparative" <?= $setting['scoring_method'] == 'comparative' ? 'selected' : '' ?>>Comparative Scoring</option>
                                                    <option value="elimination" <?= $setting['scoring_method'] == 'elimination' ? 'selected' : '' ?>>Elimination</option>
                                                    <option value="head_to_head" <?= $setting['scoring_method'] == 'head_to_head' ? 'selected' : '' ?>>Head to Head</option>
                                                    <option value="battle" <?= $setting['scoring_method'] == 'battle' ? 'selected' : '' ?>>Battle Format</option>
                                                </select>
                                            </div>
                                        </div>
                                        
                                        <div class="col-lg-6">
                                            <h6 class="text-muted mb-3">Course & Judging</h6>
                                            
                                            <div class="row">
                                                <div class="col-md-6">
                                                    <div class="mb-3">
                                                        <label class="form-label fw-semibold">Course Length</label>
                                                        <div class="input-group">
                                                            <input type="number" class="form-control" 
                                                                   name="course_length[<?= $h ?>]" 
                                                                   value="<?= $setting['course_length'] ?>"
                                                                   min="0" step="1">
                                                            <span class="input-group-text">meters</span>
                                                        </div>
                                                        <div class="form-text">0 = not applicable</div>
                                                    </div>
                                                </div>
                                                
                                                <div class="col-md-6">
                                                    <div class="mb-3">
                                                        <label class="form-label fw-semibold">Time Limit</label>
                                                        <div class="input-group">
                                                            <input type="number" class="form-control" 
                                                                   name="time_limit[<?= $h ?>]" 
                                                                   value="<?= $setting['time_limit'] ?>"
                                                                   min="0" step="1">
                                                            <span class="input-group-text">seconds</span>
                                                        </div>
                                                        <div class="form-text">0 = no limit</div>
                                                    </div>
                                                </div>
                                            </div>
                                            
                                            <div class="mb-3">
                                                <label class="form-label fw-semibold">Required Figures</label>
                                                <textarea class="form-control" rows="3"
                                                          name="required_figures[<?= $h ?>]" 
                                                          placeholder="List required figures/maneuvers..."><?= htmlspecialchars(is_array($setting['required_figures']) ? implode("\n", $setting['required_figures']) : $setting['required_figures']) ?></textarea>
                                            </div>
                                            
                                            <div class="mb-3">
                                                <label class="form-label fw-semibold">Judges Required</label>
                                                <input type="number" class="form-control" 
                                                       name="judges_required[<?= $h ?>]" 
                                                       value="<?= $setting['judges_required'] ?>"
                                                       min="1" max="15">
                                                <div class="form-text">Number of judges needed</div>
                                            </div>
                                            
                                            <div class="row">
                                                <div class="col-md-4">
                                                    <div class="mb-3">
                                                        <label class="form-label fw-semibold">Score Min</label>
                                                        <input type="number" class="form-control" 
                                                               name="scale_min[<?= $h ?>]" 
                                                               value="<?= $setting['scale_min'] ?>"
                                                               step="0.01">
                                                    </div>
                                                </div>
                                                
                                                <div class="col-md-4">
                                                    <div class="mb-3">
                                                        <label class="form-label fw-semibold">Score Max</label>
                                                        <input type="number" class="form-control" 
                                                               name="scale_max[<?= $h ?>]" 
                                                               value="<?= $setting['scale_max'] ?>"
                                                               step="0.01">
                                                    </div>
                                                </div>
                                                
                                                <div class="col-md-4">
                                                    <div class="mb-3">
                                                        <label class="form-label fw-semibold">Precision</label>
                                                        <select class="form-select" name="precision_decimal[<?= $h ?>]">
                                                            <option value="0" <?= $setting['precision_decimal'] == 0 ? 'selected' : '' ?>>Whole Numbers</option>
                                                            <option value="1" <?= $setting['precision_decimal'] == 1 ? 'selected' : '' ?>>1 Decimal</option>
                                                            <option value="2" <?= $setting['precision_decimal'] == 2 ? 'selected' : '' ?>>2 Decimals</option>
                                                        </select>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                    
                                    <div class="row">
                                        <div class="col-12">
                                            <div class="mb-3">
                                                <div class="form-check form-switch">
                                                    <input class="form-check-input" type="checkbox" 
                                                           name="weather_dependent[<?= $h ?>]" value="1"
                                                           id="weather_modal_<?= $h ?>"
                                                           <?= $setting['weather_dependent'] ? 'checked' : '' ?>>
                                                    <label class="form-check-label" for="weather_modal_<?= $h ?>">
                                                        <i class="fas fa-cloud-sun me-1"></i>Weather Dependent Competition
                                                    </label>
                                                </div>
                                                <div class="form-text">Check if this heat is affected by weather conditions</div>
                                            </div>
                                            
                                            <div class="mb-3">
                                                <label class="form-label fw-semibold">Format Description</label>
                                                <textarea class="form-control" rows="3"
                                                          name="format_description[<?= $h ?>]" 
                                                          placeholder="Additional format-specific details, rules, or requirements for this heat"><?= htmlspecialchars($setting['format_description'] ?? '') ?></textarea>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                                
                                <!-- Flow Control Tab -->
                                <div class="tab-pane fade" id="flow-<?= $h ?>" role="tabpanel">
                                    <div class="row">
                                        <div class="col-md-8">
                                            <div class="border-0 shadow-none card">
                                                <div class="border-0 shadow-none card-header">
                                                    <h6 class="mb-0">
                                                        <i class="fas fa-sitemap me-2"></i>Flow Configuration
                                                    </h6>
                                                </div>
                                                <div class="border-0 shadow-none card-body">
                                                    <div class="mb-3">
                                                        <label class="form-label fw-semibold">Flow Type</label>
                                                        <select class="form-select" name="flow_type[<?= $h ?>]" 
                                                                onchange="toggleFlowConfigModal(<?= $h ?>)">
                                                            <option value="none" <?= $setting['flow_type'] == 'none' ? 'selected' : '' ?>>
                                                                No Flow (Manual Entry)
                                                            </option>
                                                            <option value="promotion" <?= $setting['flow_type'] == 'promotion' ? 'selected' : '' ?>>
                                                                Promotion from Previous Heat
                                                            </option>
                                                            <option value="qualifying" <?= $setting['flow_type'] == 'qualifying' ? 'selected' : '' ?>>
                                                                Qualifying Heat (Best from Categories)
                                                            </option>
                                                        </select>
                                                    </div>
                                                    
                                                    <div id="flow_config_modal_<?= $h ?>" class="<?= $setting['flow_type'] !== 'none' ? '' : 'd-none' ?>">
                                                        <?php if ($h > 1): ?>
                                                            <div class="mb-3">
                                                                <label class="form-label fw-semibold">Source Heat(s) <span class="badge bg-info">Multi-select</span></label>
                                                                <select class="form-select" name="flow_source_heat[<?= $h ?>][]" multiple size="<?= min($h - 1, 5) ?>">
                                                                    <?php 
                                                                    // Parse existing source heats (could be JSON array or single value)
                                                                    $selected_heats = [];
                                                                    if (!empty($setting['flow_source_heat'])) {
                                                                        $decoded = json_decode($setting['flow_source_heat'], true);
                                                                        $selected_heats = is_array($decoded) ? $decoded : [$setting['flow_source_heat']];
                                                                    }
                                                                    ?>
                                                                    <?php for ($source_h = 1; $source_h < $h; $source_h++): ?>
                                                                        <option value="<?= $source_h ?>" 
                                                                                data-heat-number="<?= $source_h ?>"
                                                                                <?= in_array($source_h, $selected_heats) ? 'selected' : '' ?>>
                                                                            Heat <?= $source_h ?><?= !empty($heat_settings[$source_h]['heat_name']) ? ' (' . htmlspecialchars($heat_settings[$source_h]['heat_name']) . ')' : '' ?>
                                                                        </option>
                                                                    <?php endfor; ?>
                                                                </select>
                                                                <div class="form-text">
                                                                    <i class="fas fa-info-circle me-1"></i>Hold Ctrl (Cmd on Mac) to select multiple source heats
                                                                </div>
                                                            </div>
                                                        <?php endif; ?>
                                                        
                                                        <div class="mb-3">
                                                            <label class="form-label fw-semibold">Participants to Promote per Category</label>
                                                            <input type="number" class="form-control" 
                                                                   name="flow_participants_per_category[<?= $h ?>]"
                                                                   value="<?= $setting['flow_participants_per_category'] ?>"
                                                                   min="1"
                                                                   data-heat="<?= $h ?>">
                                                            <div class="form-text">
                                                                Number of top participants from each category to advance to this heat
                                                            </div>
                                                        </div>
                                                        
                                                        <div class="mb-3">
                                                            <label class="form-label fw-semibold">
                                                                Position Range 
                                                                <span class="badge bg-secondary ms-1">Optional</span>
                                                            </label>
                                                            <input type="text" class="form-control" 
                                                                   name="flow_position_range[<?= $h ?>]"
                                                                   value="<?= htmlspecialchars($setting['flow_position_range'] ?? '') ?>"
                                                                   placeholder="e.g., 1-3, 4-8, 9-12"
                                                                   pattern="\d+-\d+"
                                                                   data-heat="<?= $h ?>">
                                                            <div class="form-text">
                                                                <i class="fas fa-info-circle me-1"></i>
                                                                Specify position range from source heat (e.g., "3-4" for 3rd and 4th place, "4-15" for positions 4-15).
                                                                <br>Leave empty to use top N participants per category.
                                                            </div>
                                                        </div>
                                                        
                                                        <div class="alert alert-info">
                                                            <i class="fas fa-info-circle me-2"></i>
                                                            Flow configuration will automatically populate participants based on results from the source heat.
                                                        </div>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                        
                                        <div class="col-md-4">
                                            <div class="border-0 shadow-none card">
                                                <div class="border-0 shadow-none card-header">
                                                    <h6 class="mb-0">
                                                        <i class="fas fa-info-circle me-2"></i>Flow Info
                                                    </h6>
                                                </div>
                                                <div class="border-0 shadow-none card-body">
                                                    <div class="text-center">
                                                        <div class="mb-2">
                                                            <i class="fas fa-arrow-right fa-2x text-primary"></i>
                                                        </div>
                                                        <h6 class="text-primary">Automatic</h6>
                                                        <small class="text-muted">
                                                            Participants will be automatically populated based on your flow configuration
                                                        </small>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                                
                                <!-- Activation Tab -->
                                <div class="tab-pane fade" id="activation-<?= $h ?>" role="tabpanel">
                                    <div class="row">
                                        <div class="col-md-8">
                                            <!-- Active Heat Selection -->
                                            <div class="border-0 shadow-none card">
                                                <div class="border-0 shadow-none card-header">
                                                    <h6 class="mb-0">
                                                        <i class="fas fa-power-off me-2"></i>Heat Activation
                                                    </h6>
                                                </div>
                                                <div class="border-0 shadow-none card-body">
                                                    <div class="form-check form-switch mb-3">
                                                        <input class="form-check-input" type="radio" name="is_active" 
                                                               value="<?= $h ?>" id="active_modal_<?= $h ?>"
                                                               <?= $setting['is_active'] ? 'checked' : '' ?>
                                                               onchange="toggleActiveHeatModal(<?= $h ?>)">
                                                        <label class="form-check-label fw-semibold" for="active_modal_<?= $h ?>">
                                                            Set as Active Heat
                                                        </label>
                                                    </div>
                                                    
                                                    <?php if ($setting['is_active']): ?>
                                                        <div class="alert alert-success">
                                                            <i class="fas fa-check-circle me-2"></i>
                                                            This heat is currently active and receiving all scoring activity
                                                        </div>
                                                    <?php else: ?>
                                                        <div class="alert alert-light">
                                                            <i class="fas fa-info-circle me-2"></i>
                                                            This heat is inactive. Select to activate for scoring.
                                                        </div>
                                                    <?php endif; ?>
                                                </div>
                                            </div>
                                            
                                            <!-- Active Run Selection -->
                                            <div id="run_selector_modal_<?= $h ?>" class="card mt-3 <?= $setting['is_active'] ? '' : 'd-none' ?>">
                                                <div class="border-0 shadow-none card-header">
                                                    <h6 class="mb-0">
                                                        <i class="fas fa-play me-2"></i>Active Run Selection
                                                    </h6>
                                                </div>
                                                <div class="border-0 shadow-none card-body">
                                                    <div class="row">
                                                        <?php for ($r = 1; $r <= max(1, $setting['runs_count']); $r++): ?>
                                                            <div class="col-auto">
                                                                <div class="form-check">
                                                                    <input class="form-check-input" type="radio" 
                                                                           name="active_run[<?= $h ?>]" value="<?= $r ?>" 
                                                                           id="run_modal_<?= $h ?>_<?= $r ?>" 
                                                                           <?= $r === $setting['active_run'] ? 'checked' : '' ?>>
                                                                    <label class="form-check-label" for="run_modal_<?= $h ?>_<?= $r ?>">
                                                                        Run <?= $r ?>
                                                                    </label>
                                                                </div>
                                                            </div>
                                                        <?php endfor; ?>
                                                    </div>
                                                    <div class="form-text mt-2">
                                                        Select which run is currently active for scoring
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                        
                                        <div class="col-md-4">
                                            <div class="border-0 shadow-none card">
                                                <div class="border-0 shadow-none card-header">
                                                    <h6 class="mb-0">
                                                        <i class="fas fa-chart-line me-2"></i>Heat Status
                                                    </h6>
                                                </div>
                                                <div class="border-0 shadow-none card-body">
                                                    <div class="text-center">
                                                        <?php if ($setting['is_active']): ?>
                                                            <div class="text-success mb-2">
                                                                <i class="fas fa-fire fa-2x"></i>
                                                            </div>
                                                            <h6 class="text-success">ACTIVE</h6>
                                                            <small class="text-muted">Receiving all scores</small>
                                                        <?php else: ?>
                                                            <div class="text-muted mb-2">
                                                                <i class="fas fa-pause fa-2x"></i>
                                                            </div>
                                                            <h6 class="text-muted">INACTIVE</h6>
                                                            <small class="text-muted">Not receiving scores</small>
                                                        <?php endif; ?>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                                
                                <!-- Scoring Layout Tab -->
                                <div class="tab-pane fade" id="scoring-layout-<?= $h ?>" role="tabpanel">
                                    <?php
                                        // Get current heat-specific scoring layout config
                                        $heatLayoutConfig = [];
                                        if (!empty($setting['scoring_layout_config'])) {
                                            $heatLayoutConfig = json_decode($setting['scoring_layout_config'], true) ?? [];
                                        }
                                        
                                        // Get event-level default config
                                        $eventLayoutConfig = [];
                                        if (!empty($event_data['scoring_layout_config'])) {
                                            $eventLayoutConfig = json_decode($event_data['scoring_layout_config'], true) ?? [];
                                        }
                                        
                                        // Define available components for judge scoring panel
                                        $scoringComponents = [
                                            'criteriaInputGrid' => [
                                                'title' => 'Criteria Scoring Grid',
                                                'description' => 'Individual criteria input fields with sliders for detailed scoring',
                                                'category' => 'scoring'
                                            ],
                                            'finalCalculatedScore' => [
                                                'title' => 'Final Score Display',
                                                'description' => 'Shows the final calculated score from criteria or manual input',
                                                'category' => 'scoring'
                                            ],
                                            'figuresCard' => [
                                                'title' => 'Figures Selection Card',
                                                'description' => 'Figure selection chips for snowboard/freestyle sports',
                                                'category' => 'figures'
                                            ],
                                            'diversityValidation' => [
                                                'title' => 'Diversity Validation',
                                                'description' => 'Real-time figure diversity rule checking and warnings',
                                                'category' => 'figures'
                                            ],
                                            'figureHistory' => [
                                                'title' => 'Figure History',
                                                'description' => 'Previous figure selections across runs for reference',
                                                'category' => 'figures'
                                            ],
                                            'latestScores' => [
                                                'title' => 'Latest Scores Table',
                                                'description' => 'Recent scores with edit/overwrite functionality',
                                                'category' => 'history'
                                            ],
                                            'otherHeatScores' => [
                                                'title' => 'Other Judges Scores',
                                                'description' => 'Scores from other judges for the same participant',
                                                'category' => 'history'
                                            ],
                                            'formatInfo' => [
                                                'title' => 'Format Information Card',
                                                'description' => 'Scoring format details, rules, and metadata',
                                                'category' => 'info'
                                            ]
                                        ];
                                        
                                        // Group components by category
                                        $componentsByCategory = [];
                                        foreach ($scoringComponents as $key => $component) {
                                            $componentsByCategory[$component['category']][$key] = $component;
                                        }
                                    ?>
                                    
                                    <div class="row">
                                        <div class="col-lg-8">
                                            <div class="alert alert-info mb-4">
                                                <i class="fas fa-info-circle me-2"></i>
                                                <strong>Heat-Specific Layout:</strong> Configure which components are visible on the judge scoring panel for this heat only. 
                                                Leave unchecked to inherit from event-level settings.
                                            </div>
                                            
                                            <?php foreach ($componentsByCategory as $categoryName => $components): ?>
                                                <div class="card mb-3">
                                                    <div class="card-header">
                                                        <h6 class="mb-0">
                                                            <?php
                                                                $categoryIcons = [
                                                                    'scoring' => 'fas fa-calculator',
                                                                    'figures' => 'fas fa-snowflake',
                                                                    'history' => 'fas fa-history', 
                                                                    'info' => 'fas fa-info-circle'
                                                                ];
                                                                $categoryTitles = [
                                                                    'scoring' => 'Scoring Components',
                                                                    'figures' => 'Figure Selection',
                                                                    'history' => 'Score History',
                                                                    'info' => 'Information'
                                                                ];
                                                            ?>
                                                            <i class="<?= $categoryIcons[$categoryName] ?? 'fas fa-cube' ?> me-2"></i>
                                                            <?= $categoryTitles[$categoryName] ?? ucfirst($categoryName) ?>
                                                        </h6>
                                                    </div>
                                                    <div class="card-body">
                                                        <?php foreach ($components as $key => $component): ?>
                                                            <?php
                                                                // Check if heat has override, otherwise use event default
                                                                $heatEnabled = $heatLayoutConfig['cards'][$key]['enabled'] ?? null;
                                                                $eventEnabled = $eventLayoutConfig['cards'][$key]['enabled'] ?? true;
                                                                $hasOverride = $heatEnabled !== null;
                                                                $isEnabled = $heatEnabled ?? $eventEnabled;
                                                            ?>
                                                            <div class="mb-3 p-2 <?= $hasOverride ? 'bg-light border rounded' : '' ?>">
                                                                <div class="form-check">
                                                                    <input class="form-check-input" type="hidden" 
                                                                           name="heat_scoring_layout[<?= $h ?>][cards][<?= $key ?>][enabled]" value="0">
                                                                    <input class="form-check-input" type="checkbox" 
                                                                           name="heat_scoring_layout[<?= $h ?>][cards][<?= $key ?>][enabled]" 
                                                                           id="heat_layout_<?= $h ?>_<?= $key ?>" 
                                                                           value="1" <?= $isEnabled ? 'checked' : '' ?>>
                                                                    <label class="form-check-label" for="heat_layout_<?= $h ?>_<?= $key ?>">
                                                                        <strong><?= htmlspecialchars($component['title']) ?></strong>
                                                                        <?php if ($hasOverride): ?>
                                                                            <span class="badge bg-primary ms-2">Heat Override</span>
                                                                        <?php else: ?>
                                                                            <span class="badge bg-secondary ms-2">From Event</span>
                                                                        <?php endif; ?>
                                                                        <br>
                                                                        <small class="text-muted"><?= htmlspecialchars($component['description']) ?></small>
                                                                    </label>
                                                                </div>
                                                            </div>
                                                        <?php endforeach; ?>
                                                    </div>
                                                </div>
                                            <?php endforeach; ?>
                                        </div>
                                        
                                        <div class="col-lg-4">
                                            <div class="card">
                                                <div class="card-header">
                                                    <h6 class="mb-0">
                                                        <i class="fas fa-cogs me-2"></i>Layout Options
                                                    </h6>
                                                </div>
                                                <div class="card-body">
                                                    <div class="mb-3">
                                                        <label class="form-label">Display Mode</label>
                                                        <select class="form-select form-select-sm" 
                                                                name="heat_scoring_layout[<?= $h ?>][layout][compactMode]">
                                                            <option value="">Use Event Default</option>
                                                            <option value="0" <?= ($heatLayoutConfig['layout']['compactMode'] ?? null) === false ? 'selected' : '' ?>>Full Size Cards</option>
                                                            <option value="1" <?= ($heatLayoutConfig['layout']['compactMode'] ?? null) === true ? 'selected' : '' ?>>Compact Mode</option>
                                                        </select>
                                                    </div>
                                                    
                                                    <div class="mb-3">
                                                        <div class="form-check">
                                                            <input class="form-check-input" type="checkbox" 
                                                                   name="heat_scoring_layout[<?= $h ?>][layout][hideEmptyCards]" 
                                                                   id="heat_hideEmpty_<?= $h ?>" value="1" 
                                                                   <?= ($heatLayoutConfig['layout']['hideEmptyCards'] ?? true) ? 'checked' : '' ?>>
                                                            <label class="form-check-label" for="heat_hideEmpty_<?= $h ?>">
                                                                Hide Empty Cards
                                                            </label>
                                                        </div>
                                                    </div>
                                                    
                                                    <hr>
                                                    
                                                    <div class="alert alert-warning">
                                                        <i class="fas fa-exclamation-triangle me-2"></i>
                                                        <strong>Note:</strong> Heat-specific settings override event defaults only for this heat.
                                                    </div>
                                                    
                                                    <button type="button" class="btn btn-outline-secondary btn-sm w-100" 
                                                            onclick="resetHeatLayout(<?= $h ?>)">
                                                        <i class="fas fa-undo me-1"></i>Reset to Event Defaults
                                                    </button>
                                                </div>
                                            </div>
                                            
                                            <div class="card mt-3">
                                                <div class="card-header">
                                                    <h6 class="mb-0">
                                                        <i class="fas fa-eye me-2"></i>Preview
                                                    </h6>
                                                </div>
                                                <div class="card-body">
                                                    <p class="text-muted mb-2">Enabled components for judges:</p>
                                                    <div id="layoutPreview_<?= $h ?>" class="small">
                                                        <!-- Will be populated by JavaScript -->
                                                    </div>
                                                    <hr>
                                                    <a href="../judge/score.php?event_id=<?= $selected_event_id ?>&heat=<?= $h ?>" 
                                                       target="_blank" class="btn btn-outline-primary btn-sm w-100">
                                                        <i class="fas fa-external-link-alt me-1"></i>
                                                        Test Judge Panel
                                                    </a>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                        
                        <div class="modal-footer">
                            <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">
                                <i class="fas fa-times me-1"></i>Cancel
                            </button>
                            <button type="submit" class="btn btn-success">
                                <i class="fas fa-save me-1"></i>Save Heat Configuration
                            </button>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    <?php endforeach; ?>

    <?php elseif ($selected_event_id): ?>
        <div class="alert alert-warning">
            <i class="fas fa-exclamation-triangle me-2"></i>
            This event has no heats defined (heats_total = 0). 
            <a href="events.php" class="alert-link">Edit the event</a> to set the number of heats.
        </div>
    <?php endif; ?>
        </div>

</div></div>
        

</div>

<script>
// Modal functions
function testModal() {
    console.log('Test modal function called');
    alert('Test function works! Bootstrap available: ' + (typeof bootstrap !== 'undefined'));
    
    if (typeof bootstrap !== 'undefined') {
        // Try to open the first heat modal
        const firstModal = document.querySelector('[id^="heatModal"]');
        if (firstModal) {
            console.log('Found modal:', firstModal.id);
            try {
                const modal = new bootstrap.Modal(firstModal);
                modal.show();
                console.log('Modal opened successfully');
            } catch (error) {
                console.error('Error opening modal:', error);
                alert('Error: ' + error.message);
            }
        } else {
            alert('No modal found');
        }
    }
}

function openHeatModal(heatNumber) {
    console.log('Opening modal for heat:', heatNumber);
    
    // Wait a bit for Bootstrap to be fully loaded if needed
    setTimeout(() => {
        // Check if Bootstrap is available
        if (typeof bootstrap === 'undefined') {
            console.error('Bootstrap is not loaded!');
            alert('Bootstrap is not loaded. Please refresh the page.');
            return;
        }
        
        const modalElement = document.getElementById('heatModal' + heatNumber);
        if (!modalElement) {
            console.error('Modal element not found:', 'heatModal' + heatNumber);
            alert('Modal not found for heat ' + heatNumber);
            return;
        }
        
        try {
            const modal = new bootstrap.Modal(modalElement);
            modal.show();
            
            // Initialize the modal content
            setTimeout(() => {
                updateRunOptionsModal(heatNumber);
                calculateEstimatedFinishModal(heatNumber);
                toggleFlowConfigModal(heatNumber);
                
                // Update button text in main card when modal opens
                updateHeatButtonDisplay(heatNumber);
            }, 100);
            
            console.log('Modal opened successfully for heat:', heatNumber);
        } catch (error) {
            console.error('Error opening modal:', error);
            alert('Error opening modal: ' + error.message);
        }
    }, 50);
}

function activateHeat(heatNumber) {
    // Store the heat number for later use
    window.pendingActivateHeat = heatNumber;
    
    // Get heat settings
    const heat = window.heatSettings[heatNumber] || {};
    const runsCount = heat.runs_count || 1;
    
    // Update modal titles
    document.getElementById('activateHeatNumber').textContent = heatNumber;
    document.getElementById('confirmHeatNumber').textContent = heatNumber;
    
    // Check for currently active heat
    let activeHeat = null;
    for (const heatNum in window.heatSettings) {
        if (window.heatSettings[heatNum].status === 'active') {
            activeHeat = {
                number: heatNum,
                name: window.heatSettings[heatNum].heat_name || 'Unnamed Heat'
            };
            break;
        }
    }
    
    // Show/hide warning about active heat
    const warningDiv = document.getElementById('activeHeatWarning');
    if (activeHeat && activeHeat.number != heatNumber) {
        document.getElementById('currentActiveHeatNumber').textContent = activeHeat.number;
        document.getElementById('currentActiveHeatName').textContent = activeHeat.name;
        warningDiv.classList.remove('d-none');
    } else {
        warningDiv.classList.add('d-none');
    }
    
    // Generate run selection buttons
    const runSelectionDiv = document.getElementById('runSelectionOptions');
    let runButtons = '';
    
    for (let i = 1; i <= runsCount; i++) {
        const isFirst = i === 1;
        runButtons += `
            <button type="button" class="btn btn-outline-success ${isFirst ? 'active' : ''}" 
                    onclick="selectActivateRun(${i})" 
                    data-run="${i}" 
                    id="activateRunBtn_${i}">
                <i class="fas fa-play-circle me-2"></i>Run ${i}
            </button>
        `;
    }
    
    runSelectionDiv.innerHTML = runButtons;
    
    // Set default selected run
    window.selectedActivateRun = 1;
    
    // Show the modal
    const modal = new bootstrap.Modal(document.getElementById('activateHeatModal'));
    modal.show();
}

function selectActivateRun(runNumber) {
    // Update selected run
    window.selectedActivateRun = runNumber;
    
    // Update button states
    document.querySelectorAll('#runSelectionOptions button').forEach(btn => {
        btn.classList.remove('active');
    });
    document.getElementById('activateRunBtn_' + runNumber).classList.add('active');
}

function confirmActivateHeat() {
    const heatNumber = window.pendingActivateHeat;
    const runNumber = window.selectedActivateRun || 1;
    const eventId = <?= json_encode($selected_event_id) ?>;
    
    if (!eventId || !heatNumber) {
        alert('Invalid heat selection');
        return;
    }
    
    // Create form and submit
    const form = document.createElement('form');
    form.method = 'POST';
    form.action = window.location.href;
    
    // Add event_id
    const eventInput = document.createElement('input');
    eventInput.type = 'hidden';
    eventInput.name = 'event_id';
    eventInput.value = eventId;
    form.appendChild(eventInput);
    
    // Add save_settings flag
    const saveInput = document.createElement('input');
    saveInput.type = 'hidden';
    saveInput.name = 'save_settings';
    saveInput.value = '1';
    form.appendChild(saveInput);
    
    // Add is_active (which heat to activate)
    const activeInput = document.createElement('input');
    activeInput.type = 'hidden';
    activeInput.name = 'is_active';
    activeInput.value = heatNumber;
    form.appendChild(activeInput);
    
    // Add active_run for the heat being activated
    const runInput = document.createElement('input');
    runInput.type = 'hidden';
    runInput.name = 'active_run[' + heatNumber + ']';
    runInput.value = runNumber;
    form.appendChild(runInput);
    
    // Add all required heat data to maintain existing settings
    const heat = window.heatSettings[heatNumber] || {};
    
    // Add heat_name
    const nameInput = document.createElement('input');
    nameInput.type = 'hidden';
    nameInput.name = 'heat_name[' + heatNumber + ']';
    nameInput.value = heat.heat_name || '';
    form.appendChild(nameInput);
    
    // Add other required fields
    const fields = {
        'scoring_type': heat.scoring_type || 'Points',
        'runs_count': heat.runs_count || 1,
        'runs_scoring_method': heat.runs_scoring_method || 'best_from_all',
        'time_start': heat.time_start || '',
        'estimate_time_per_participant': heat.estimate_time_per_participant || 0,
        'flow_type': heat.flow_type || 'none',
        'flow_source_heat': heat.flow_source_heat || '',
        'flow_participants_per_category': heat.flow_participants_per_category || 0,
        'flow_position_range': heat.flow_position_range || ''
    };
    
    for (const [fieldName, fieldValue] of Object.entries(fields)) {
        const input = document.createElement('input');
        input.type = 'hidden';
        input.name = fieldName + '[' + heatNumber + ']';
        input.value = fieldValue;
        form.appendChild(input);
    }
    
    // Submit the form
    document.body.appendChild(form);
    form.submit();
}

// Heat Cards AJAX Loading
let heatCardsRefreshTimer = null;
let currentRefreshInterval = 30; // Default 30 seconds

function loadHeatCards(showLoading = true) {
    const eventId = <?= json_encode($selected_event_id) ?>;
    const container = document.getElementById('heat-buttons-container');
    
    if (!eventId) {
        container.innerHTML = '<div class="col-12"><div class="alert alert-warning">No event selected</div></div>';
        return;
    }
    
    if (showLoading) {
        const refreshBtn = document.querySelector('[onclick="loadHeatCards()"]');
        if (refreshBtn) {
            const icon = refreshBtn.querySelector('i');
            if (icon) {
                icon.classList.add('fa-spin');
            }
        }
    }
    
    fetch('heat_cards_api.php?event_id=' + eventId)
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                container.innerHTML = data.data;
                
                // Update last refresh time
                const now = new Date();
                const timeStr = now.toLocaleTimeString();
                const lastRefreshEl = document.getElementById('lastRefreshTime');
                if (lastRefreshEl) {
                    lastRefreshEl.textContent = 'Last: ' + timeStr;
                }
                
                console.log('Heat cards loaded:', data.heat_count, 'heats at', data.timestamp);
            } else {
                container.innerHTML = '<div class="col-12"><div class="alert alert-danger">Error: ' + (data.message || 'Failed to load heat cards') + '</div></div>';
            }
        })
        .catch(error => {
            console.error('Error loading heat cards:', error);
            container.innerHTML = '<div class="col-12"><div class="alert alert-danger">Network error loading heat cards</div></div>';
        })
        .finally(() => {
            // Stop spinning icon
            const refreshBtn = document.querySelector('[onclick="loadHeatCards()"]');
            if (refreshBtn) {
                const icon = refreshBtn.querySelector('i');
                if (icon) {
                    icon.classList.remove('fa-spin');
                }
            }
        });
}

function setRefreshInterval() {
    const select = document.getElementById('refreshInterval');
    const interval = parseInt(select.value);
    
    // Clear existing timer
    if (heatCardsRefreshTimer) {
        clearInterval(heatCardsRefreshTimer);
        heatCardsRefreshTimer = null;
    }
    
    currentRefreshInterval = interval;
    
    if (interval > 0) {
        // Set up auto-refresh
        heatCardsRefreshTimer = setInterval(() => {
            loadHeatCards(false); // Load without showing loading state
        }, interval * 1000);
        
        console.log('Auto-refresh enabled:', interval, 'seconds');
    } else {
        console.log('Auto-refresh disabled (manual mode)');
    }
}

function showHeatResults(heatNumber) {
    const eventId = <?= json_encode($selected_event_id) ?>;
    
    if (!eventId) {
        alert('No event selected');
        return;
    }
    
    // Get heat name from heat settings
    const heat = window.heatSettings[heatNumber] || {};
    const heatName = heat.heat_name || 'Unnamed Heat';
    
    // Update modal title with heat number and name
    document.getElementById('resultsHeatNumber').textContent = heatNumber;
    document.getElementById('resultsHeatName').textContent = heatName;
    
    // Show the modal
    const modal = new bootstrap.Modal(document.getElementById('heatResultsModal'));
    modal.show();
    
    // Load configurations for this heat
    loadHeatConfigurations(eventId, heatNumber);
}

function loadHeatConfigurations(eventId, heatNumber) {
    const configsList = document.getElementById('savedConfigsList');
    
    // Show loading state
    configsList.innerHTML = `
        <div class="text-center py-3 text-muted">
            <div class="spinner-border spinner-border-sm" role="status">
                <span class="visually-hidden">Loading...</span>
            </div>
            <p class="mt-2 small">Loading configurations...</p>
        </div>
    `;
    
    // Fetch all configurations for the event
    fetch(`../api/public_dashboard_api.php?action=get_configurations&event_id=${eventId}`)
        .then(response => response.json())
        .then(data => {
            if (!data.success || !data.configurations || data.configurations.length === 0) {
                configsList.innerHTML = `
                    <div class="alert alert-warning mb-0 small">
                        <i class="fas fa-exclamation-triangle me-2"></i>
                        No saved reports found for this event.
                    </div>
                `;
                return;
            }
            
            // Use all configurations (no filtering)
            const allConfigs = data.configurations;
            
            // Build configuration list
            let html = '';
            allConfigs.forEach((config, index) => {
                const isActive = index === 0 ? 'active' : '';
                const viewTypeIcon = config.view_type === 'start_list' ? 'fa-list-ol' : 'fa-table';
                const viewTypeLabel = config.view_type === 'start_list' ? 'Start List' : 'Summary';
                const heatLabel = config.heat_number ? `Heat ${config.heat_number}` : 'All Heats';
                
                html += `
                    <button type="button" 
                            class="list-group-item list-group-item-action config-button ${isActive}"
                            data-config-id="${config.id}"
                            onclick="loadHeatConfiguration(${config.id}, '${config.view_type}')"
                            title="Click to load">
                        <div class="d-flex flex-column">
                            <div class="d-flex justify-content-between align-items-start mb-1">
                                <span class="me-2 text-start flex-grow-1">
                                    <i class="fas ${viewTypeIcon} me-2"></i>${escapeHtml(config.name)}
                                </span>
                                <span class="badge bg-light text-dark">${viewTypeLabel}</span>
                            </div>
                            <small class="text-muted">
                                <i class="fas fa-fire me-1"></i>${heatLabel}
                            </small>
                        </div>
                    </button>
                `;
            });
            
            configsList.innerHTML = html;
            
            // Auto-load first configuration
            if (allConfigs.length > 0) {
                loadHeatConfiguration(allConfigs[0].id, allConfigs[0].view_type);
            }
        })
        .catch(error => {
            console.error('Error loading configurations:', error);
            configsList.innerHTML = `
                <div class="alert alert-danger mb-0 small">
                    <i class="fas fa-times-circle me-2"></i>
                    Error loading configurations: ${escapeHtml(error.message)}
                </div>
            `;
        });
}

function loadHeatConfiguration(configId, viewType) {
    const contentDisplay = document.getElementById('resultsContentDisplay');
    
    // Update active state
    document.querySelectorAll('#savedConfigsList .config-button').forEach(btn => {
        btn.classList.remove('active');
    });
    document.querySelector(`[data-config-id="${configId}"]`)?.classList.add('active');
    
    // Show loading
    contentDisplay.innerHTML = `
        <div class="text-center py-5">
            <div class="spinner-border text-primary" role="status">
                <span class="visually-hidden">Loading...</span>
            </div>
            <p class="mt-2 text-muted">Loading results...</p>
        </div>
    `;
    
    // Determine API endpoint based on view type
    const apiEndpoint = viewType === 'start_list' 
        ? '../api/start_list_api.php' 
        : '../api/summary_table_api.php';
    
    // Load configuration
    fetch(`${apiEndpoint}?config_id=${configId}&format=html`)
        .then(response => {
            if (!response.ok) {
                throw new Error(`HTTP ${response.status}`);
            }
            return response.text();
        })
        .then(html => {
            contentDisplay.innerHTML = html;
        })
        .catch(error => {
            console.error('Error loading configuration:', error);
            contentDisplay.innerHTML = `
                <div class="alert alert-danger">
                    <i class="fas fa-exclamation-triangle me-2"></i>
                    Error loading results: ${error.message}
                </div>
            `;
        });
}

function escapeHtml(text) {
    const div = document.createElement('div');
    div.textContent = text;
    return div.innerHTML;
}

function changeActiveRun(heatNumber, direction) {
    const eventId = <?= json_encode($selected_event_id) ?>;
    
    if (!eventId) {
        alert('No event selected');
        return;
    }
    
    // Confirm the change
    const action = direction > 0 ? 'next' : 'previous';
    if (!confirm(`Change to ${action} run for Heat ${heatNumber}?`)) {
        return;
    }
    
    // Submit via form
    const form = document.createElement('form');
    form.method = 'POST';
    form.action = window.location.href;
    
    const eventInput = document.createElement('input');
    eventInput.type = 'hidden';
    eventInput.name = 'event_id';
    eventInput.value = eventId;
    form.appendChild(eventInput);
    
    const actionInput = document.createElement('input');
    actionInput.type = 'hidden';
    actionInput.name = 'change_active_run';
    actionInput.value = '1';
    form.appendChild(actionInput);
    
    const heatInput = document.createElement('input');
    heatInput.type = 'hidden';
    heatInput.name = 'heat_number';
    heatInput.value = heatNumber;
    form.appendChild(heatInput);
    
    const directionInput = document.createElement('input');
    directionInput.type = 'hidden';
    directionInput.name = 'direction';
    directionInput.value = direction;
    form.appendChild(directionInput);
    
    document.body.appendChild(form);
    form.submit();
}

function closeHeat(heatNumber) {
    const eventId = <?= json_encode($selected_event_id) ?>;
    
    if (!eventId) {
        alert('No event selected');
        return;
    }
    
    // Confirm closing the heat
    if (!confirm(`Are you sure you want to mark Heat ${heatNumber} as FINISHED?\n\nThis will complete the heat and stop all scoring activity.`)) {
        return;
    }
    
    // Submit via form
    const form = document.createElement('form');
    form.method = 'POST';
    form.action = window.location.href;
    
    const eventInput = document.createElement('input');
    eventInput.type = 'hidden';
    eventInput.name = 'event_id';
    eventInput.value = eventId;
    form.appendChild(eventInput);
    
    const actionInput = document.createElement('input');
    actionInput.type = 'hidden';
    actionInput.name = 'close_heat';
    actionInput.value = '1';
    form.appendChild(actionInput);
    
    const heatInput = document.createElement('input');
    heatInput.type = 'hidden';
    heatInput.name = 'heat_number';
    heatInput.value = heatNumber;
    form.appendChild(heatInput);
    
    document.body.appendChild(form);
    form.submit();
}

function cancelHeat(heatNumber) {
    const eventId = <?= json_encode($selected_event_id) ?>;
    
    if (!eventId) {
        alert('No event selected');
        return;
    }
    
    // Confirm cancelling the heat
    if (!confirm(`Are you sure you want to CANCEL Heat ${heatNumber}?\n\nThis will mark the heat as cancelled.`)) {
        return;
    }
    
    // Submit via form
    const form = document.createElement('form');
    form.method = 'POST';
    form.action = window.location.href;
    
    const eventInput = document.createElement('input');
    eventInput.type = 'hidden';
    eventInput.name = 'event_id';
    eventInput.value = eventId;
    form.appendChild(eventInput);
    
    const actionInput = document.createElement('input');
    actionInput.type = 'hidden';
    actionInput.name = 'cancel_heat';
    actionInput.value = '1';
    form.appendChild(actionInput);
    
    const heatInput = document.createElement('input');
    heatInput.type = 'hidden';
    heatInput.name = 'heat_number';
    heatInput.value = heatNumber;
    form.appendChild(heatInput);
    
    document.body.appendChild(form);
    form.submit();
}

function rescheduleHeat(heatNumber) {
    const eventId = <?= json_encode($selected_event_id) ?>;
    
    if (!eventId) {
        alert('No event selected');
        return;
    }
    
    // Confirm rescheduling the heat
    if (!confirm(`Mark Heat ${heatNumber} for RESCHEDULING?\n\nThis will set the heat status to rescheduled.`)) {
        return;
    }
    
    // Submit via form
    const form = document.createElement('form');
    form.method = 'POST';
    form.action = window.location.href;
    
    const eventInput = document.createElement('input');
    eventInput.type = 'hidden';
    eventInput.name = 'event_id';
    eventInput.value = eventId;
    form.appendChild(eventInput);
    
    const actionInput = document.createElement('input');
    actionInput.type = 'hidden';
    actionInput.name = 'reschedule_heat';
    actionInput.value = '1';
    form.appendChild(actionInput);
    
    const heatInput = document.createElement('input');
    heatInput.type = 'hidden';
    heatInput.name = 'heat_number';
    heatInput.value = heatNumber;
    form.appendChild(heatInput);
    
    document.body.appendChild(form);
    form.submit();
}

function setPendingHeat(heatNumber) {
    const eventId = <?= json_encode($selected_event_id) ?>;
    
    if (!eventId) {
        alert('No event selected');
        return;
    }
    
    // Confirm setting heat to pending
    if (!confirm(`Set Heat ${heatNumber} to PENDING status?\n\nThis will deactivate the heat and return it to pending state.`)) {
        return;
    }
    
    // Submit via form
    const form = document.createElement('form');
    form.method = 'POST';
    form.action = window.location.href;
    
    const eventInput = document.createElement('input');
    eventInput.type = 'hidden';
    eventInput.name = 'event_id';
    eventInput.value = eventId;
    form.appendChild(eventInput);
    
    const actionInput = document.createElement('input');
    actionInput.type = 'hidden';
    actionInput.name = 'set_pending_heat';
    actionInput.value = '1';
    form.appendChild(actionInput);
    
    const heatInput = document.createElement('input');
    heatInput.type = 'hidden';
    heatInput.name = 'heat_number';
    heatInput.value = heatNumber;
    form.appendChild(heatInput);
    
    document.body.appendChild(form);
    form.submit();
}

function updateHeatButtonDisplay(heatNumber) {
    // Update the button text and heat name display in the main cards when data changes
    const heatNameInput = document.querySelector(`input[name="heat_name[${heatNumber}]"]`);
    if (heatNameInput) {
        // Update card display based on modal input
        heatNameInput.addEventListener('input', function() {
            const cardText = document.querySelector(`#heat-buttons-container .card:nth-child(${heatNumber}) .card-text`);
            if (cardText) {
                cardText.textContent = this.value.trim() || 'Unnamed Heat';
            }
        });
    }
}

// Modal-specific functions (copies of existing functions with modal suffix)
function toggleActiveHeatModal(heatNumber) {
    // Show/hide run selector in modal
    const runSelector = document.getElementById(`run_selector_modal_${heatNumber}`);
    const isActive = document.getElementById(`active_modal_${heatNumber}`).checked;
    
    if (runSelector) {
        if (isActive) {
            runSelector.classList.remove('d-none');
        } else {
            runSelector.classList.add('d-none');
        }
    }
}

function toggleAllCategoriesModal(heatNumber) {
    const allCheckbox = document.getElementById(`all_categories_modal_${heatNumber}`);
    const categoryCheckboxes = document.querySelectorAll(`input[data-heat="${heatNumber}"].category-checkbox`);
    
    if (allCheckbox.checked) {
        categoryCheckboxes.forEach(checkbox => {
            checkbox.checked = false;
            checkbox.disabled = true;
        });
    } else {
        categoryCheckboxes.forEach(checkbox => {
            checkbox.disabled = false;
        });
    }
}

function updateCategorySelectionModal(heatNumber) {
    const allCheckbox = document.getElementById(`all_categories_modal_${heatNumber}`);
    const categoryCheckboxes = document.querySelectorAll(`input[data-heat="${heatNumber}"].category-checkbox:checked`);
    
    if (categoryCheckboxes.length > 0) {
        allCheckbox.checked = false;
    }
}

function toggleFlowConfigModal(heatNumber) {
    const flowType = document.querySelector(`select[name="flow_type[${heatNumber}]"]`).value;
    const flowConfig = document.getElementById(`flow_config_modal_${heatNumber}`);
    const participantsInput = document.querySelector(`input[name="flow_participants_per_category[${heatNumber}]"]`);
    const sourceHeatSelect = document.querySelector(`select[name="flow_source_heat[${heatNumber}]"]`);
    
    if (flowType !== 'none') {
        flowConfig.classList.remove('d-none');
        if (participantsInput) {
            participantsInput.removeAttribute('disabled');
            participantsInput.setAttribute('min', '1');
        }
        if (sourceHeatSelect) {
            sourceHeatSelect.removeAttribute('disabled');
        }
    } else {
        flowConfig.classList.add('d-none');
        if (participantsInput) {
            participantsInput.setAttribute('disabled', 'disabled');
            participantsInput.removeAttribute('min');
        }
        if (sourceHeatSelect) {
            sourceHeatSelect.setAttribute('disabled', 'disabled');
        }
    }
}

function calculateEstimatedFinishModal(heatNumber) {
    const startTime = document.querySelector(`input[name="time_start[${heatNumber}]"]`).value;
    const timePerParticipant = parseInt(document.querySelector(`input[name="estimate_time_per_participant[${heatNumber}]"]`).value) || 0;
    
    if (startTime && timePerParticipant > 0) {
        // Get actual participant count for this heat
        const participantCount = window.heatParticipantCounts ? window.heatParticipantCounts[heatNumber] || 0 : 0;
        
        if (participantCount > 0) {
            const totalSeconds = timePerParticipant * participantCount;
            const totalMinutes = Math.ceil(totalSeconds / 60);
            
            const [hours, minutes] = startTime.split(':').map(Number);
            const startDateTime = new Date();
            startDateTime.setHours(hours, minutes, 0, 0);
            
            const finishDateTime = new Date(startDateTime.getTime() + (totalMinutes * 60000));
            const finishTime = finishDateTime.toTimeString().slice(0, 5);
            
            const finishElement = document.getElementById(`finish_time_modal_${heatNumber}`);
            if (finishElement) {
                finishElement.textContent = `${finishTime} (${totalMinutes} minutes for ${participantCount} participants)`;
                document.getElementById(`estimated_finish_modal_${heatNumber}`).classList.remove('d-none');
            }
        } else {
            const finishElement = document.getElementById(`finish_time_modal_${heatNumber}`);
            if (finishElement) {
                finishElement.textContent = 'No participants assigned to this heat yet';
                document.getElementById(`estimated_finish_modal_${heatNumber}`).classList.remove('d-none');
            }
        }
    } else {
        const estimatedElement = document.getElementById(`estimated_finish_modal_${heatNumber}`);
        if (estimatedElement) {
            estimatedElement.classList.add('d-none');
        }
    }
}

function updateRunOptionsModal(heatNumber) {
    const runsCount = parseInt(document.querySelector(`select[name="runs_count[${heatNumber}]"]`).value);
    const scoringSelect = document.getElementById(`runs_scoring_modal_${heatNumber}`);
    
    if (!scoringSelect) return;
    
    // Store current selection to try to maintain it
    const currentValue = scoringSelect.value;
    
    // Clear existing options
    scoringSelect.innerHTML = '';
    
    // Generate scoring options based on runs count
    const scoringOptions = generateScoringOptions(runsCount);
    
    // Get the saved value from PHP for this heat
    const savedValue = 'best_from_all'; // Default fallback
    
    scoringOptions.forEach(option => {
        const optionElement = document.createElement('option');
        optionElement.value = option.value;
        optionElement.textContent = option.text;
        
        // Set selected if it matches saved value or current value
        if (option.value === savedValue || option.value === currentValue) {
            optionElement.selected = true;
        }
        
        scoringSelect.appendChild(optionElement);
    });
    
    // If no option was selected and we have options, select the first one
    if (!scoringSelect.value && scoringOptions.length > 0) {
        scoringSelect.value = scoringOptions[0].value;
    }
    
    // Update explanation
    updateScoringExplanationModal(heatNumber);
    
    // Update run selector for active heat selection
    updateRunSelectorModal(heatNumber);
}

function updateScoringExplanationModal(heatNumber) {
    const scoringSelect = document.getElementById(`runs_scoring_modal_${heatNumber}`);
    const explanationSpan = document.getElementById(`scoring_explanation_modal_${heatNumber}`);
    
    if (!scoringSelect || !explanationSpan) return;
    
    const selectedValue = scoringSelect.value;
    
    const explanations = {
        'single_run': 'Score from the single run attempt',
        'best_from_2': 'Highest score from 2 runs',
        'average_from_2': 'Average score from both runs',
        'best_from_3': 'Highest score from 3 runs',
        'average_best_2_from_3': 'Average of the 2 highest scores from 3 runs',
        'average_from_3': 'Average score from all 3 runs',
        'best_from_4': 'Highest score from 4 runs',
        'average_best_2_from_4': 'Average of the 2 highest scores from 4 runs',
        'average_best_3_from_4': 'Average of the 3 highest scores from 4 runs',
        'average_from_4': 'Average score from all 4 runs',
        'best_from_5': 'Highest score from 5 runs',
        'average_best_2_from_5': 'Average of the 2 highest scores from 5 runs',
        'average_best_3_from_5': 'Average of the 3 highest scores from 5 runs',
        'average_best_4_from_5': 'Average of the 4 highest scores from 5 runs',
        'average_from_5': 'Average score from all 5 runs'
    };
    
    explanationSpan.textContent = explanations[selectedValue] || 'How to calculate final score from multiple runs';
}

function updateRunSelectorModal(heatNumber) {
    const runsCount = parseInt(document.querySelector(`select[name="runs_count[${heatNumber}]"]`).value);
    const runSelector = document.getElementById(`run_selector_modal_${heatNumber}`);
    
    if (!runSelector) return;
    
    // Rebuild run radio buttons
    const runOptions = Array.from({length: runsCount}, (_, i) => {
        const runNum = i + 1;
        return `
            <div class="col-auto">
                <div class="form-check">
                    <input class="form-check-input" type="radio" 
                           name="active_run[${heatNumber}]" value="${runNum}" 
                           id="run_modal_${heatNumber}_${runNum}" ${runNum === 1 ? 'checked' : ''}>
                    <label class="form-check-label" for="run_modal_${heatNumber}_${runNum}">
                        Run ${runNum}
                    </label>
                </div>
            </div>
        `;
    }).join('');
    
    const runsContainer = runSelector.querySelector('.row');
    if (runsContainer) {
        runsContainer.innerHTML = runOptions;
    }
}

function validateHeatForm(heatNumber) {
    let isValid = true;
    const errors = [];
    
    // Check flow configuration
    const flowType = document.querySelector(`select[name="flow_type[${heatNumber}]"]`);
    if (flowType) {
        const flowTypeValue = flowType.value;
        
        if (flowTypeValue !== 'none') {
            const participantsInput = document.querySelector(`input[name="flow_participants_per_category[${heatNumber}]"]`);
            const participantsValue = participantsInput ? parseInt(participantsInput.value) || 0 : 0;
            
            if (participantsValue < 1) {
                errors.push(`Please specify number of participants to promote (minimum 1)`);
                isValid = false;
            }
            
            if (flowTypeValue === 'promotion') {
                const sourceHeat = document.querySelector(`select[name="flow_source_heat[${heatNumber}]"]`);
                const sourceHeatValue = sourceHeat ? sourceHeat.value : '';
                if (!sourceHeatValue) {
                    errors.push(`Please select a source heat for promotion flow`);
                    isValid = false;
                }
            }
        }
    }
    
    if (!isValid) {
        alert('Please fix the following errors:\n\n' + errors.join('\n'));
        return false;
    }
    
    return true;
}

function generateScoringOptions(runsCount) {
    const options = [];
    
    if (runsCount === 1) {
        options.push({
            value: 'single_run',
            text: 'Single Run Score'
        });
    } else if (runsCount === 2) {
        options.push(
            {
                value: 'best_from_2',
                text: 'Best from 2 Runs'
            },
            {
                value: 'average_from_2',
                text: 'Average from 2 Runs'
            }
        );
    } else if (runsCount === 3) {
        options.push(
            {
                value: 'best_from_3',
                text: 'Best from 3 Runs'
            },
            {
                value: 'average_best_2_from_3',
                text: 'Average of Best 2 from 3 Runs'
            },
            {
                value: 'average_from_3',
                text: 'Average from 3 Runs'
            }
        );
    } else if (runsCount === 4) {
        options.push(
            {
                value: 'best_from_4',
                text: 'Best from 4 Runs'
            },
            {
                value: 'average_best_2_from_4',
                text: 'Average of Best 2 from 4 Runs'
            },
            {
                value: 'average_best_3_from_4',
                text: 'Average of Best 3 from 4 Runs'
            },
            {
                value: 'average_from_4',
                text: 'Average from 4 Runs'
            }
        );
    } else if (runsCount === 5) {
        options.push(
            {
                value: 'best_from_5',
                text: 'Best from 5 Runs'
            },
            {
                value: 'average_best_2_from_5',
                text: 'Average of Best 2 from 5 Runs'
            },
            {
                value: 'average_best_3_from_5',
                text: 'Average of Best 3 from 5 Runs'
            },
            {
                value: 'average_best_4_from_5',
                text: 'Average of Best 4 from 5 Runs'
            },
            {
                value: 'average_from_5',
                text: 'Average from 5 Runs'
            }
        );
    }
    
    return options;
}

function updateScoringExplanation(heatNumber) {
    const scoringSelect = document.getElementById(`runs_scoring_${heatNumber}`);
    const explanationSpan = document.getElementById(`scoring_explanation_${heatNumber}`);
    
    if (!scoringSelect || !explanationSpan) return;
    
    const selectedValue = scoringSelect.value;
    
    const explanations = {
        'single_run': 'Score from the single run attempt',
        'best_from_2': 'Highest score from 2 runs',
        'average_from_2': 'Average score from both runs',
        'best_from_3': 'Highest score from 3 runs',
        'average_best_2_from_3': 'Average of the 2 highest scores from 3 runs',
        'average_from_3': 'Average score from all 3 runs',
        'best_from_4': 'Highest score from 4 runs',
        'average_best_2_from_4': 'Average of the 2 highest scores from 4 runs',
        'average_best_3_from_4': 'Average of the 3 highest scores from 4 runs',
        'average_from_4': 'Average score from all 4 runs',
        'best_from_5': 'Highest score from 5 runs',
        'average_best_2_from_5': 'Average of the 2 highest scores from 5 runs',
        'average_best_3_from_5': 'Average of the 3 highest scores from 5 runs',
        'average_best_4_from_5': 'Average of the 4 highest scores from 5 runs',
        'average_from_5': 'Average score from all 5 runs'
    };
    
    explanationSpan.textContent = explanations[selectedValue] || 'How to calculate final score from multiple runs';
}

function updateRunSelector(heatNumber) {
    const runsCount = parseInt(document.querySelector(`select[name="runs_count[${heatNumber}]"]`).value);
    const runSelector = document.getElementById(`run_selector_${heatNumber}`);
    
    if (!runSelector) return;
    
    // Rebuild run radio buttons
    const runOptions = Array.from({length: runsCount}, (_, i) => {
        const runNum = i + 1;
        return `
            <div class="col-auto">
                <div class="form-check">
                    <input class="form-check-input" type="radio" 
                           name="active_run[${heatNumber}]" value="${runNum}" 
                           id="run_${heatNumber}_${runNum}" ${runNum === 1 ? 'checked' : ''}>
                    <label class="form-check-label" for="run_${heatNumber}_${runNum}">
                        Run ${runNum}
                    </label>
                </div>
            </div>
        `;
    }).join('');
    
    const runsContainer = runSelector.querySelector('.row');
    if (runsContainer) {
        runsContainer.innerHTML = runOptions;
    }
}

function updateRunOptions(heatNumber) {
    const runsCount = parseInt(document.querySelector(`select[name="runs_count[${heatNumber}]"]`).value);
    const scoringSelect = document.getElementById(`runs_scoring_${heatNumber}`);
    
    if (!scoringSelect) return;
    
    // Store current selection to try to maintain it
    const currentValue = scoringSelect.value;
    
    // Clear existing options
    scoringSelect.innerHTML = '';
    
    // Generate scoring options based on runs count
    const scoringOptions = generateScoringOptions(runsCount);
    
    // Get the saved value from PHP for this heat
    const savedValue = '<?= $setting['runs_scoring_method'] ?? 'best_from_all' ?>';
    
    scoringOptions.forEach(option => {
        const optionElement = document.createElement('option');
        optionElement.value = option.value;
        optionElement.textContent = option.text;
        
        // Set selected if it matches saved value or current value
        if (option.value === savedValue || option.value === currentValue) {
            optionElement.selected = true;
        }
        
        scoringSelect.appendChild(optionElement);
    });
    
    // If no option was selected and we have options, select the first one
    if (!scoringSelect.value && scoringOptions.length > 0) {
        scoringSelect.value = scoringOptions[0].value;
    }
    
    // Update explanation
    updateScoringExplanation(heatNumber);
    
    // Update run selector for active heat selection
    updateRunSelector(heatNumber);
}

function attachScoringMethodListeners() {
    <?php foreach ($heat_order as $h): ?>
        const scoringSelect_<?= $h ?> = document.getElementById(`runs_scoring_<?= $h ?>`);
        if (scoringSelect_<?= $h ?>) {
            scoringSelect_<?= $h ?>.addEventListener('change', function() {
                updateScoringExplanation(<?= $h ?>);
            });
        }
    <?php endforeach; ?>
}

function toggleActiveHeat(heatNumber) {
    // Hide all run selectors
    document.querySelectorAll('.run-selector').forEach(selector => {
        selector.classList.add('d-none');
    });
    
    // Remove active styles from all heat cards
    document.querySelectorAll('.heat-card').forEach(card => {
        card.classList.remove('border-success', 'bg-success-subtle');
        card.classList.add('opacity-75');
    });
    
    // Show run selector for active heat
    const runSelector = document.getElementById(`run_selector_${heatNumber}`);
    if (runSelector) {
        runSelector.classList.remove('d-none');
    }
    
    // Add active class to selected heat card
    const activeCard = document.querySelector(`input[value="${heatNumber}"]`).closest('.heat-card');
    if (activeCard) {
        activeCard.classList.add('border-success', 'bg-success-subtle');
        activeCard.classList.remove('opacity-75');
    }
}

function toggleAllCategories(heatNumber) {
    const allCheckbox = document.getElementById(`all_categories_${heatNumber}`);
    const categoryCheckboxes = document.querySelectorAll(`input[data-heat="${heatNumber}"].category-checkbox`);
    
    if (allCheckbox.checked) {
        categoryCheckboxes.forEach(checkbox => {
            checkbox.checked = false;
            checkbox.disabled = true;
        });
    } else {
        categoryCheckboxes.forEach(checkbox => {
            checkbox.disabled = false;
        });
    }
}

function updateCategorySelection(heatNumber) {
    const allCheckbox = document.getElementById(`all_categories_${heatNumber}`);
    const categoryCheckboxes = document.querySelectorAll(`input[data-heat="${heatNumber}"].category-checkbox:checked`);
    
    if (categoryCheckboxes.length > 0) {
        allCheckbox.checked = false;
    }
}

function toggleFlowConfig(heatNumber) {
    const flowType = document.querySelector(`select[name="flow_type[${heatNumber}]"]`);
    if (!flowType) return;
    
    const flowTypeValue = flowType.value;
    const flowConfig = document.getElementById(`flow_config_${heatNumber}`);
    const participantsInput = document.querySelector(`input[name="flow_participants_per_category[${heatNumber}]"]`);
    const sourceHeatSelect = document.querySelector(`select[name="flow_source_heat[${heatNumber}]"]`);
    
    if (flowTypeValue !== 'none') {
        if (flowConfig) flowConfig.classList.remove('d-none');
        if (participantsInput) {
            participantsInput.removeAttribute('disabled');
            participantsInput.setAttribute('min', '1');
        }
        if (sourceHeatSelect) {
            sourceHeatSelect.removeAttribute('disabled');
        }
    } else {
        if (flowConfig) flowConfig.classList.add('d-none');
        if (participantsInput) {
            participantsInput.setAttribute('disabled', 'disabled');
            participantsInput.removeAttribute('min');
        }
        if (sourceHeatSelect) {
            sourceHeatSelect.setAttribute('disabled', 'disabled');
        }
    }
}

function calculateEstimatedFinish(heatNumber) {
    const startTime = document.querySelector(`input[name="time_start[${heatNumber}]"]`).value;
    const timePerParticipant = parseInt(document.querySelector(`input[name="estimate_time_per_participant[${heatNumber}]"]`).value) || 0;
    
    if (startTime && timePerParticipant > 0) {
        // Get actual participant count for this heat
        const participantCount = window.heatParticipantCounts ? window.heatParticipantCounts[heatNumber] || 0 : 0;
        
        if (participantCount > 0) {
            const totalSeconds = timePerParticipant * participantCount;
            const totalMinutes = Math.ceil(totalSeconds / 60);
            
            const [hours, minutes] = startTime.split(':').map(Number);
            const startDateTime = new Date();
            startDateTime.setHours(hours, minutes, 0, 0);
            
            const finishDateTime = new Date(startDateTime.getTime() + (totalMinutes * 60000));
            const finishTime = finishDateTime.toTimeString().slice(0, 5);
            
            const finishElement = document.getElementById(`finish_time_${heatNumber}`);
            if (finishElement) {
                finishElement.textContent = `${finishTime} (${totalMinutes} minutes for ${participantCount} participants)`;
                document.getElementById(`estimated_finish_${heatNumber}`).classList.remove('d-none');
            }
        } else {
            const finishElement = document.getElementById(`finish_time_${heatNumber}`);
            if (finishElement) {
                finishElement.textContent = 'No participants assigned to this heat yet';
                document.getElementById(`estimated_finish_${heatNumber}`).classList.remove('d-none');
            }
        }
    } else {
        const estimatedElement = document.getElementById(`estimated_finish_${heatNumber}`);
        if (estimatedElement) {
            estimatedElement.classList.add('d-none');
        }
    }
}

function updateHeatNameDisplay(heatNumber) {
    const nameInput = document.querySelector(`input[name="heat_name[${heatNumber}]"]`);
    const nameDisplay = document.getElementById(`heat_name_display_${heatNumber}`);
    
    if (nameInput && nameDisplay) {
        const name = nameInput.value.trim();
        nameDisplay.textContent = name ? `(${name})` : '';
    }
}

function updateHeatNameReferences(changedHeatNumber) {
    const nameInput = document.querySelector(`input[name="heat_name[${changedHeatNumber}]"]`);
    const newName = nameInput ? nameInput.value.trim() : '';
    
    // Update all source heat dropdowns that reference this heat
    document.querySelectorAll(`option[data-heat-number="${changedHeatNumber}"]`).forEach(option => {
        const heatNumber = changedHeatNumber;
        const baseText = `Heat ${heatNumber}`;
        option.textContent = newName ? `${baseText} (${newName})` : baseText;
    });
    
    // Update the heat name display
    updateHeatNameDisplay(changedHeatNumber);
    
    // Update flow visualization if visible
    updateFlowDisplay();
}


function showNotification(message, type = 'info') {
    // Create notification element
    const notification = document.createElement('div');
    notification.className = `alert alert-${type} alert-dismissible fade show position-fixed top-0 end-0 mt-3 me-3 shadow w-auto`;
    notification.innerHTML = `
        <i class="fas fa-${type === 'success' ? 'check-circle' : 'info-circle'} me-2"></i>
        ${message}
        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
    `;
    
    document.body.appendChild(notification);
    
    // Auto-remove after 3 seconds
    setTimeout(() => {
        if (notification.parentNode) {
            notification.remove();
        }
    }, 3000);
}

function updateFlowDisplay() {
    // This would update the flow visualization section if it's visible
    console.log('Flow display updated');
}

function validateForm() {
    let isValid = true;
    const errors = [];
    
    // Check each heat's flow configuration
    <?php foreach ($heat_order as $h): ?>
        const flowType_<?= $h ?> = document.querySelector(`select[name="flow_type[<?= $h ?>]"]`);
        if (flowType_<?= $h ?>) {
            const flowTypeValue = flowType_<?= $h ?>.value;
            
            if (flowTypeValue !== 'none') {
                const participantsInput_<?= $h ?> = document.querySelector(`input[name="flow_participants_per_category[<?= $h ?>]"]`);
                const participantsValue_<?= $h ?> = participantsInput_<?= $h ?> ? parseInt(participantsInput_<?= $h ?>.value) || 0 : 0;
                
                if (participantsValue_<?= $h ?> < 1) {
                    errors.push(`Heat <?= $h ?>: Please specify number of participants to promote (minimum 1)`);
                    isValid = false;
                }
                
                <?php if ($h > 1): ?>
                    if (flowTypeValue === 'promotion') {
                        const sourceHeat_<?= $h ?> = document.querySelector(`select[name="flow_source_heat[<?= $h ?>]"]`);
                        const sourceHeatValue = sourceHeat_<?= $h ?> ? sourceHeat_<?= $h ?>.value : '';
                        if (!sourceHeatValue) {
                            errors.push(`Heat <?= $h ?>: Please select a source heat for promotion flow`);
                            isValid = false;
                        }
                    }
                <?php endif; ?>
            }
        }
    <?php endforeach; ?>
    
    if (!isValid) {
        alert('Please fix the following errors:\n\n' + errors.join('\n'));
        return false;
    }
    
    return true;
}

// Enhanced initialization
document.addEventListener('DOMContentLoaded', function() {
    console.log('DOM Content Loaded');
    console.log('Bootstrap available:', typeof bootstrap !== 'undefined');
    
    // Load heat cards immediately
    <?php if ($selected_event_id && $heats_total > 0): ?>
        loadHeatCards();
        
        // Set up auto-refresh with default interval (30s)
        setRefreshInterval();
    <?php endif; ?>
    
    // Test function - add simple click listener
    document.querySelectorAll('[onclick*="openHeatModal"]').forEach(button => {
        console.log('Found button with openHeatModal:', button);
    });
    
    // Make participant counts available to JavaScript
    const heatParticipantCounts = <?= json_encode($heat_participant_counts ?? []) ?>;
    window.heatParticipantCounts = heatParticipantCounts;
    
    // Make heat settings available to JavaScript
    const heatSettings = <?= json_encode($heat_settings ?? []) ?>;
    window.heatSettings = heatSettings;
    
    // Initialize run options and scoring methods for all heats
    <?php foreach ($heat_order as $h): ?>
        // Initialize each heat with proper values
        (function(heatNum) {
            const savedScoringMethod = '<?= $heat_settings[$h]['runs_scoring_method'] ?? 'best_from_all' ?>';
            
            // Update run options first
            updateRunOptions(heatNum);
            
            // Set the saved scoring method
            const scoringSelect = document.getElementById(`runs_scoring_${heatNum}`);
            if (scoringSelect && savedScoringMethod) {
                scoringSelect.value = savedScoringMethod;
                updateScoringExplanation(heatNum);
            }
            
            calculateEstimatedFinish(heatNum);
            toggleFlowConfig(heatNum);
            
            // Initialize category selection
            <?php if (empty($heat_settings[$h]['categories'] ?? [])): ?>
                toggleAllCategories(heatNum);
            <?php endif; ?>
            
            // Attach heat name change listeners
            const nameInput = document.querySelector(`input[name="heat_name[${heatNum}]"]`);
            if (nameInput) {
                nameInput.addEventListener('input', function() {
                    updateHeatNameDisplay(heatNum);
                });
                nameInput.addEventListener('change', function() {
                    updateHeatNameReferences(heatNum);
                });
            }
        })(<?= $h ?>);
    <?php endforeach; ?>
    
    // Attach scoring method listeners
    attachScoringMethodListeners();
    
    // Show run selector for active heat
    const activeHeatRadio = document.querySelector('input[name="is_active"]:checked');
    if (activeHeatRadio) {
        toggleActiveHeat(activeHeatRadio.value);
    }
    
    // Add form validation
    const form = document.querySelector('form');
    if (form) {
        form.addEventListener('submit', function(e) {
            
            if (!validateForm()) {
                e.preventDefault();
            } else {
                // Update URL with event_id parameter before submission
                c
            }
        });
    }
    
   
    // Clean up refresh timer on page unload
    window.addEventListener('beforeunload', function() {
        if (heatCardsRefreshTimer) {
            clearInterval(heatCardsRefreshTimer);
        }
    });
});

// Scoring Layout Functions
function resetHeatLayout(heatNumber) {
    if (confirm('Reset this heat\'s scoring layout to use event defaults?')) {
        // Uncheck all checkboxes for this heat
        const checkboxes = document.querySelectorAll(`input[name^="heat_scoring_layout[${heatNumber}]"]`);
        checkboxes.forEach(checkbox => {
            if (checkbox.type === 'checkbox') {
                checkbox.checked = false;
            }
        });
        
        // Reset select boxes
        const selects = document.querySelectorAll(`select[name^="heat_scoring_layout[${heatNumber}]"]`);
        selects.forEach(select => {
            select.selectedIndex = 0; // Select first option (usually "Use Event Default")
        });
        
        updateLayoutPreview(heatNumber);
        
        // Show feedback
        const alert = document.createElement('div');
        alert.className = 'alert alert-success alert-dismissible fade show mt-2';
        alert.innerHTML = `
            <i class="fas fa-check me-2"></i>
            Heat ${heatNumber} layout reset to event defaults.
            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
        `;
        
        const targetTab = document.getElementById(`scoring-layout-${heatNumber}`);
        if (targetTab) {
            targetTab.insertBefore(alert, targetTab.firstChild);
            
            // Auto dismiss after 3 seconds
            setTimeout(() => {
                if (alert.parentNode) {
                    alert.remove();
                }
            }, 3000);
        }
    }
}

function updateLayoutPreview(heatNumber) {
    const previewDiv = document.getElementById(`layoutPreview_${heatNumber}`);
    if (!previewDiv) return;
    
    const enabledComponents = [];
    const checkboxes = document.querySelectorAll(`input[name^="heat_scoring_layout[${heatNumber}][cards]"][name$="[enabled]"]:checked`);
    
    checkboxes.forEach(checkbox => {
        const match = checkbox.name.match(/\[cards\]\[([^\]]+)\]/);
        if (match) {
            const componentKey = match[1];
            const componentNames = {
                'criteriaInputGrid': 'Criteria Grid',
                'finalCalculatedScore': 'Final Score',
                'figuresCard': 'Figures',
                'diversityValidation': 'Diversity Check',
                'figureHistory': 'Figure History',
                'latestScores': 'Latest Scores',
                'otherHeatScores': 'Other Judges',
                'formatInfo': 'Format Info'
            };
            
            enabledComponents.push(componentNames[componentKey] || componentKey);
        }
    });
    
    if (enabledComponents.length > 0) {
        previewDiv.innerHTML = enabledComponents.map(name => 
            `<span class="badge bg-success me-1 mb-1">${name}</span>`
        ).join('');
    } else {
        previewDiv.innerHTML = '<em class="text-muted">All components disabled</em>';
    }
}

// Update previews when checkboxes change
document.addEventListener('DOMContentLoaded', function() {
    // Initialize layout previews for all heats
    const layoutCheckboxes = document.querySelectorAll('input[name*="heat_scoring_layout"][name*="[enabled]"]');
    layoutCheckboxes.forEach(checkbox => {
        const heatMatch = checkbox.name.match(/\[(\d+)\]/);
        if (heatMatch) {
            const heatNumber = heatMatch[1];
            
            // Update preview when checkbox changes
            checkbox.addEventListener('change', () => updateLayoutPreview(heatNumber));
            
            // Initialize preview
            updateLayoutPreview(heatNumber);
        }
    });
});
</script>

    <?php include '../admin/footer.php'; ?>
</body>
</html>