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


$selected_event = $_GET['event_id'] ?? null;
$selected_heat = $_GET['heat_number'] ?? null;
$selected_heats = [];
if ($selected_heat) {
    // Support both single heat number and comma-separated multiple heats
    $selected_heats = is_array($selected_heat) ? $selected_heat : explode(',', $selected_heat);
    $selected_heats = array_filter($selected_heats); // Remove empty values
}
$view_type = $_GET['view_type'] ?? 'start_list'; // start_list or summary_table



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

// Fetch heats for selected event
$heats = [];
$categories = [];
if ($selected_event) {
    $stmt = $pdo->prepare("SELECT heat_number, heat_name FROM event_heat_settings WHERE event_id = ? ORDER BY heat_number ASC");
    $stmt->execute([$selected_event]);
    $heats = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    // Fetch categories for the selected event
    $categories = [];
    if ($selected_event) {
        // Get participant-assigned categories for backward compatibility
        $stmt = $pdo->prepare("SELECT DISTINCT category FROM event_participants WHERE event_id = ? AND category IS NOT NULL ORDER BY category");
        $stmt->execute([$selected_event]);
        $participant_categories = $stmt->fetchAll(PDO::FETCH_COLUMN);
        
        if ($selected_heat) {
            // Get heat-specific categories from event_heat_settings.categories column
            $stmt = $pdo->prepare("
                SELECT categories 
                FROM event_heat_settings 
                WHERE event_id = ? AND heat_number = ? 
                LIMIT 1
            ");
            $stmt->execute([$selected_event, $selected_heat]);
            $heat_categories_json = $stmt->fetchColumn();
            
            if ($heat_categories_json) {
                // Parse the JSON array of category IDs
                $heat_category_ids = json_decode($heat_categories_json, true) ?: [];
                
                if (!empty($heat_category_ids)) {
                    // Create placeholders for the IN clause
                    $placeholders = implode(',', array_fill(0, count($heat_category_ids), '?'));
                    
                    // Get category details for the heat-specific categories
                    $stmt = $pdo->prepare("
                        SELECT id, category_name, is_main_category, use_for_ranking 
                        FROM event_categories 
                        WHERE event_id = ? AND id IN ($placeholders)
                        ORDER BY is_main_category DESC, category_name
                    ");
                    
                    // Combine the parameters: first the event_id, then all category IDs
                    $params = array_merge([$selected_event], $heat_category_ids);
                    $stmt->execute($params);
                    $categories = $stmt->fetchAll(PDO::FETCH_ASSOC);
                }
            }
            
            // If no categories found through heat settings, fall back to participants in the heat
            if (empty($categories)) {
                // Fallback query to find categories of participants in this heat
                $stmt = $pdo->prepare("
                    SELECT DISTINCT ec.id, ec.category_name, ec.is_main_category, ec.use_for_ranking
                    FROM event_categories ec
                    JOIN event_participants ep ON (
                        ep.event_id = ec.event_id 
                        AND (
                            ep.category_id = ec.id
                            OR (ep.matching_category_ids IS NOT NULL AND ep.matching_category_ids LIKE CONCAT('%\"',ec.id,'\"%'))
                        )
                    )
                    WHERE ec.event_id = ? AND ep.heat_number = ?
                    ORDER BY ec.is_main_category DESC, ec.category_name
                ");
                $stmt->execute([$selected_event, $selected_heat]);
                $categories = $stmt->fetchAll(PDO::FETCH_ASSOC);
            }
        } else {
            // If no heat selected, get all main + ranking categories
            $stmt = $pdo->prepare("
                SELECT id, category_name, is_main_category, use_for_ranking 
                FROM event_categories 
                WHERE event_id = ? AND (is_main_category = 1 OR use_for_ranking = 1)
                ORDER BY is_main_category DESC, category_name
            ");
            $stmt->execute([$selected_event]);
            $categories = $stmt->fetchAll(PDO::FETCH_ASSOC);
        }
        
        // Add legacy categories for backward compatibility
        foreach ($participant_categories as $cat) {
            if (!in_array($cat, array_column($categories, 'category_name'))) {
                $categories[] = [
                    'id' => null, 
                    'category_name' => $cat, 
                    'is_main_category' => 0, 
                    'use_for_ranking' => 0
                ];
            }
        }
    }
}

// Fetch saved configurations for selected event
$saved_configurations = [];
if ($selected_event) {
    $stmt = $pdo->prepare("
        SELECT id, name, view_type, heat_number, category, status, display_order, created_at
        FROM result_configurations 
        WHERE event_id = ? AND view_type = ?
        ORDER BY display_order ASC, name ASC
    ");
    $stmt->execute([$selected_event, $view_type]);
    $saved_configurations = $stmt->fetchAll(PDO::FETCH_ASSOC);
}

// Function to generate dynamic configuration name
function generateConfigName($view_type, $event_name, $heat_number = null, $category = null) {
    $name = ($view_type === 'summary_table' ? 'Summary Table' : 'Start List');
    $name .= ' - ' . $event_name;
    
    if ($heat_number) {
        $name .= ' - Heat ' . $heat_number;
    }
    
    if ($category && $category !== 'all') {
        $name .= ' - ' . $category;
    }
    
    return $name;
}


?>
<!DOCTYPE html>
<html>
<head>
    <title><?= $view_type === 'summary_table' ? 'Summary Tables' : 'Start Lists' ?></title>
    <!-- style skin holder Create & manage configurations for live results, PDFs, and data exports -->
 <?php include_once '../includes/stylesheets.php'; ?>
</head>
<body class="body-bg-aurora-bright">                 <?php       
            $use_localStorage = true;
            $show_header = false;
            include 'event_actions_menu.php'; 
            ?>
    <?php include '../menu.php'; ?>

    <div class="container-fluid container-StyleScore p-4">
   
           
        <div class="row justify-content-center">
            <div class="col-12">
                <!-- Tab Navigation -->
                 <div class="d-flex justify-content-between align-items-center ">
                       <div class="border-0 shadow-none card shadow-none card mb-3">
                            
                            <div class="border-0 shadow-none card-body p-2">
                                <div class="d-flex justify-content-between align-items-center mb-2">
                                    <div>
                                        <h6 class="mb-0 fw-bold text-primary"><i class="fas fa-calendar-alt me-2"></i>Event</h6>
                                        
                                    </div>
                                </div>
                                <form method="get" class="row g-2 load-event-selection" id="filterForm">
                                    <input type="hidden" name="view_type" value="<?= htmlspecialchars($view_type) ?>">

                                    <div class="col-12 d-flex align-items-center">
                                        
                                        <select name="event_id" id="event_id" class="form-select form-select-sm" onchange="handleEventChange()">
                                            <option value="">-- Select Event --</option>
                                            <?php foreach ($events as $event): ?>
                                                <option value="<?= $event['id'] ?>" <?= $selected_event == $event['id'] ? 'selected' : '' ?>>
                                                    <?= htmlspecialchars($event['name']) ?>
                                                </option>
                                            <?php endforeach; ?>
                                        </select>
                                    </div>
                                </form>
                            </div>
                        </div>
                            <div class="m-0">
                                <ul class="nav nav-tabs h5" id="viewTabs" role="tablist">
                                    <li class="nav-item" role="presentation">
                                        <button class="p-2 nav-link <?= $view_type === 'start_list' ? 'active' : '' ?>" 
                                                onclick="switchView('start_list')" type="button">
                                            <i class="fas fa-list-ol me-2"></i>Start Lists
                                        </button>
                                    </li>
                                    <li class="nav-item" role="presentation">
                                        <button class="p-2 nav-link <?= $view_type === 'summary_table' ? 'active' : '' ?>" 
                                                onclick="switchView('summary_table')" type="button">
                                            <i class="fas fa-table me-2"></i>Summary Tables
                                        </button>
                                    </li>
                                </ul>
                            </div>

                
                    
                    
                    <!-- Help Button -->
                    <button type="button" class="btn btn-outline-primary btn-sm" data-bs-toggle="modal" data-bs-target="#helpModal" title="Help & Documentation">
                        <i class="fas fa-question-circle me-1"></i>Help
                    </button>
                </div>
                <div class="row">
                    <!-- Left Column: Filters -->
                    <div class="col-md-3">
                     

                                     <!-- Configuration Management -->
                <?php if ($selected_event): ?>
                <div class="border-0 shadow-none card mb-3" id="configManagementCard">
                    <div class="card shadow-none card-body p-2 ">
                        <div class="d-flex justify-content-between align-items-center mb-2">
                            <div>
                                <h6 class="mb-0 fw-bold text-primary">
                                    <i class="fas fa-cog me-2"></i>
                                    <?php if ($view_type === 'summary_table'): ?>
                                        Summary Table Management
                                    <?php else: ?>
                                        Start Lists Management
                                    <?php endif; ?>
                                </h6>
                               
                            </div>
                            
                        </div>
                        
                        <!-- Quick Access Bar for Saved Configurations -->
                        <?php if (!empty($saved_configurations)): ?>
                        <div class="mt-2">
                            <div class="d-flex flex-wrap align-items-center gap-2 mb-2">
                                
                                <div class="input-group input-group-sm" style="">
                                    <input type="text" id="configSearch" class="form-control form-control-sm" 
                                           placeholder="Search..." onkeyup="filterConfigs()">
                                    <button class="btn btn-outline-secondary" type="button" onclick="clearConfigSearch()">
                                        <i class="fas fa-times"></i>
                                    </button>
                                </div>
                                <button class="btn btn-danger btn-sm" id="bulkDeleteBtn" style="display: none;" onclick="bulkDeleteConfigs()">
                                    <i class="fas fa-trash"></i> Delete
                                </button>
                            </div>
                            
                            <!-- Compact Configuration List -->
                            <div class="list-group" id="configCards">
                                <?php foreach ($saved_configurations as $config): ?>
                                <div class="config-card border-b list-group-item p-1" data-config-name="<?= strtolower($config['name']) ?>" data-config-type="<?= $config['view_type'] ?>" data-config-status="<?= $config['status'] ?>">
                                    <div class="p-2 config-item" data-config-id="<?= $config['id'] ?>">
                                        <div class="d-flex align-items-center">
                                            <!-- Selection Checkbox -->
                                            <div class="form-check me-2">
                                                <input class="form-check-input config-select-checkbox" type="checkbox" 
                                                       value="<?= $config['id'] ?>" id="config_cb_<?= $config['id'] ?>" 
                                                       onchange="updateBulkDeleteButton()">
                                            </div>
                                            
                                            <!-- Favorite Star -->
                                            <?php if (isset($config['is_favorite']) && $config['is_favorite']): ?>
                                                <i class="fas fa-star text-warning me-2"></i>
                                            <?php else: ?>
                                                
                                            <?php endif; ?>
                                            
                                            <!-- Main Content -->
                                            <div class="flex-grow-1 min-w-0" onclick="loadConfiguration(<?= $config['id'] ?>)" style="cursor: pointer;">
                                                <?php 
                                                // Clean display name by removing document type prefixes
                                                $displayName = $config['name'];
                                                $displayName = preg_replace('/^(Start List|Summary Table)\s*-\s*/', '', $displayName);
                                                ?>
                                                <div class="d-flex align-items-center mb-1">
                                                    <span onclick="loadConfiguration(<?= $config['id'] ?>)" class="fw-semibold text-truncate me-2" style="font-size: 0.85rem;" title="<?= htmlspecialchars($displayName) ?>">
                                                        <?= htmlspecialchars($displayName) ?>
                                                    </span>
                                                    
                                                </div>
                                                <div class="d-flex align-items-center text-muted" style="font-size: 0.7rem;">
                                                    <?php if ($config['category']): ?>
                                                        <span class="text-truncate me-2">
                                                            <i class="fas fa-tag me-1"></i><?= htmlspecialchars($config['category']) ?>
                                                        </span>
                                                    <?php endif; ?>
                                                    <span>
                                                        <i class="fas fa-calendar me-1"></i><?= date('M j H:i', strtotime($config['created_at'])) ?>
                                                    </span>
                                                    
                                                </div>
                                                <div class="d-flex gap-1" >
                                                        <span class="badge bg-light text-dark" style="font-size: 0.6rem;">
                                                        #<?= htmlspecialchars($config['id']) ?>
                                                        </span>
                                                        <span class="badge bg-light text-dark" style="font-size: 0.6rem;">
                                                            <?= $config['view_type'] === 'summary_table' ? '<small class="text-info"><i class="fas fa-table me-1"></i>Summary Table</small>' : '<small class="text-success"><i class="fas fa-list-ul me-1"></i>Start List</small>' ?>
                                                        </span>
                                                        <span class="badge bg-<?= $config['status'] === 'active' ? 'success' : ($config['status'] === 'public' ? 'primary' : 'secondary') ?>" style="font-size: 0.6rem;">
                                                            <?= ucfirst($config['status']) ?>
                                                        </span>
                                                        <?php if ($config['heat_number']): ?>
                                                            <?php
                                                            // Format heat_number display
                                                            $heat_display = $config['heat_number'];
                                                            if (is_numeric($heat_display)) {
                                                                // Single heat number
                                                                $heat_display = "H" . $heat_display;
                                                            } else {
                                                                // Try to decode JSON array
                                                                $decoded_heats = json_decode($heat_display, true);
                                                                if (is_array($decoded_heats)) {
                                                                    $heat_count = count($decoded_heats);
                                                                    if ($heat_count <= 3) {
                                                                        // Show all heats if 3 or fewer
                                                                        $heat_display = "H" . implode(",", $decoded_heats);
                                                                    } else {
                                                                        // Show first, last, and count
                                                                        $first = $decoded_heats[0];
                                                                        $last = $decoded_heats[$heat_count - 1];
                                                                        $heat_display = "H" . $first . "-" . $last . " (" . $heat_count . ")";
                                                                    }
                                                                } else {
                                                                    // Fallback - just show "H"
                                                                    $heat_display = "H" . $heat_display;
                                                                }
                                                            }
                                                            ?>
                                                            <span class="badge bg-warning text-dark" style="font-size: 0.6rem;" title="Heats: <?= htmlspecialchars($config['heat_number']) ?>"><?= htmlspecialchars($heat_display) ?></span>
                                                        <?php endif; ?>
                                                    </div>
                                            </div>
                                            
                                            <!-- Action Buttons -->
                                            <div class="d-flex align-items-center">
                                                <button type="button" class="btn btn-primary btn-sm me-1" onclick="loadConfiguration(<?= $config['id'] ?>)" title="Load this configuration" style="padding: 0.25rem 0.5rem;">
                                                    <i class="fas fa-play" style="font-size: 0.7rem;"></i>
                                                </button>
                                                
                                                <?php if ($config['view_type'] === 'start_list'): ?>
                                                <!-- Quick Export Buttons for Start Lists -->
                                                <div class="btn-group me-1" role="group">
                                                    <button type="button" onclick="window.open('../api/start_list_api.php?config_id=<?= $config['id'] ?>&format=pdf&styling=full','_blank')" class="btn btn-sm btn-outline-danger border-0 p-0" title="Export as PDF" style="padding: 0.25rem 0.35rem !important;">
                                                        <i class="fas fa-file-pdf" style="font-size: 0.7rem;"></i>
                                                    </button>
                                                    <button type="button" onclick="window.open('../api/start_list_api.php?config_id=<?= $config['id'] ?>&format=html&styling=full','_blank')" class="btn btn-sm btn-outline-secondary border-0 p-0" title="View as HTML" style="padding: 0.25rem 0.35rem !important;">
                                                        <i class="fas fa-table" style="font-size: 0.7rem;"></i>
                                                    </button>
                                                    <button type="button" onclick="window.location.href='../api/start_list_api.php?config_id=<?= $config['id'] ?>&format=csv'" class="btn btn-sm btn-outline-primary border-0 p-0" title="Download as CSV" style="padding: 0.25rem 0.35rem !important;">
                                                        <i class="fas fa-file-csv" style="font-size: 0.7rem;"></i>
                                                    </button>
                                                    <button type="button" onclick="window.open('../api/start_list_api.php?config_id=<?= $config['id'] ?>&format=json','_blank')" class="btn btn-sm btn-outline-success border-0 p-0" title="View as JSON" style="padding: 0.25rem 0.35rem !important;">
                                                        <i class="fas fa-code" style="font-size: 0.7rem;"></i>
                                                    </button>
                                                </div>
                                                <?php endif; ?>
                                                
                                                <div class="dropdown">
                                                    <button class="btn btn-outline-secondary btn-sm" type="button" data-bs-toggle="dropdown" style="padding: 0.25rem 0.5rem;">
                                                        <i class="fas fa-ellipsis-h" style="font-size: 0.7rem;"></i>
                                                    </button>
                                                    <ul class="dropdown-menu dropdown-menu-end">
                                                        <li><a class="dropdown-item" href="#" onclick="loadConfiguration(<?= $config['id'] ?>)">
                                                            <i class="fas fa-download me-2"></i>Load
                                                        </a></li>
                                                        <li><a class="dropdown-item" href="#" onclick="previewConfiguration(<?= $config['id'] ?>)">
                                                            <i class="fas fa-eye me-2"></i>Preview
                                                        </a></li>
                                                        
                                                        <li><hr class="dropdown-divider"></li>
                                                        <li><h6 class="dropdown-header">Export Formats</h6></li>
                                                        
                                                        <?php if ($config['view_type'] === 'summary_table'): ?>
                                                        <li><a class="dropdown-item" href="#" onclick="window.open('../api/summary_table_api.php?config_id=<?= $config['id'] ?>&config_name=<?= urlencode($config['name']) ?>&format=pdf', '_blank')">
                                                            <i class="fas fa-file-pdf text-danger me-2"></i>PDF
                                                        </a></li>
                                                        <li><a class="dropdown-item" href="#" onclick="window.open('../api/summary_table_api.php?config_id=<?= $config['id'] ?>&config_name=<?= urlencode($config['name']) ?>&format=html', '_blank')">
                                                            <i class="fas fa-table text-secondary me-2"></i>HTML
                                                        </a></li>
                                                        <li><a class="dropdown-item" href="#" onclick="window.location.href='../api/summary_table_api.php?config_id=<?= $config['id'] ?>&config_name=<?= urlencode($config['name']) ?>&format=csv'">
                                                            <i class="fas fa-file-csv text-success me-2"></i>CSV
                                                        </a></li>
                                                        <li><a class="dropdown-item" href="#" onclick="window.open('../api/summary_table_api.php?config_id=<?= $config['id'] ?>&config_name=<?= urlencode($config['name']) ?>&format=json', '_blank')">
                                                            <i class="fas fa-code text-info me-2"></i>JSON
                                                        </a></li>
                                                        <?php elseif ($config['view_type'] === 'start_list'): ?>
                                                        <li><a class="dropdown-item" href="#" onclick="window.open('../api/start_list_api.php?config_id=<?= $config['id'] ?>&config_name=<?= urlencode($config['name']) ?>&format=pdf&styling=full', '_blank')">
                                                            <i class="fas fa-file-pdf text-danger me-2"></i>PDF
                                                        </a></li>
                                                        <li><a class="dropdown-item" href="#" onclick="window.open('../api/start_list_api.php?config_id=<?= $config['id'] ?>&config_name=<?= urlencode($config['name']) ?>&format=html&styling=full', '_blank')">
                                                            <i class="fas fa-table  me-2"></i>HTML
                                                        </a></li>
                                                        <li><a class="dropdown-item" href="#" onclick="window.location.href='../api/start_list_api.php?config_id=<?= $config['id'] ?>&config_name=<?= urlencode($config['name']) ?>&format=csv'">
                                                            <i class="fas fa-file-csv text-success me-2"></i>CSV
                                                        </a></li>
                                                        <li><a class="dropdown-item" href="#" onclick="window.open('../api/start_list_api.php?config_id=<?= $config['id'] ?>&config_name=<?= urlencode($config['name']) ?>&format=json', '_blank')">
                                                            <i class="fas fa-code text-info me-2"></i>JSON
                                                        </a></li>
                                                        <?php endif; ?>
                                                        <li><hr class="dropdown-divider"></li>
                                                        <li><a class="dropdown-item" href="#" onclick="duplicateConfiguration(<?= $config['id'] ?>)">
                                                            <i class="fas fa-copy me-2"></i>Duplicate
                                                        </a></li>
                                                        <li><hr class="dropdown-divider"></li>
                                                        <li><a class="dropdown-item" href="#" onclick="toggleFavorite(<?= $config['id'] ?>)">
                                                            <i class="fas fa-star me-2"></i>
                                                            <?= isset($config['is_favorite']) && $config['is_favorite'] ? 'Remove from' : 'Add to' ?> Favorites
                                                        </a></li>
                                                        <li><a class="dropdown-item" href="#" onclick="editConfiguration(<?= $config['id'] ?>)">
                                                            <i class="fas fa-edit me-2"></i>Edit
                                                        </a></li>
                                                        <li><hr class="dropdown-divider"></li>
                                                        <li><a class="dropdown-item text-danger" href="#" onclick="deleteConfiguration(<?= $config['id'] ?>, '<?= htmlspecialchars($config['name'], ENT_QUOTES) ?>')">
                                                            <i class="fas fa-trash me-2"></i>Delete
                                                        </a></li>
                                                    </ul>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                                <?php endforeach; ?>
                            </div>
                        </div>
                        <?php endif; ?>
                    </div>
                </div>
                <?php endif; ?>
                        </div>
                        
                        <!-- Right Column: Content Display -->
                        <div class="col-md-9">
                                    <?php if ($selected_event): ?>
                                      <div class="border-0 shadow-none card mb-3">
                            
                    <div class="card shadow-none card-body p-2">
                                <div class="d-flex justify-content-between align-items-center mb-2">
                                    <div class="d-flex justify-content-between align-items-center w-100">
                                        <h6 class="mb-0 fw-bold text-primary"><i class="fas fa-calendar-alt me-2"></i>Select which heat will appear on results</h6>
                                        <small class="text-muted">Narrow down the results by selecting a specific category</small>
                                    </div>
                                </div>
                        <div class="row">
                            <div class="col-3">
                                        <label for="heat_number" class="form-label mb-1 small fw-semibold">Heat Selection</label>
                                        <select name="heat_number[]" id="heat_number" class="form-select form-select-sm" multiple size="4" onchange="handleHeatChange()">
                                            <option value="">-- All Heats --</option>
                                    <?php foreach ($heats as $heat): ?>
                                        <option value="<?= $heat['heat_number'] ?>" <?= in_array($heat['heat_number'], $selected_heats) ? 'selected' : '' ?>>
                                            Heat <?= $heat['heat_number'] ?><?= $heat['heat_name'] ? ' - ' . htmlspecialchars($heat['heat_name']) : '' ?>
                                        </option>
                                    <?php endforeach; ?>
                                </select>
                                <small class="form-text text-muted">Hold Ctrl/Cmd to select multiple heats</small>
                            </div>
                            
                            <div class="col-3">
                                <label for="run_number" class="form-label mb-1 small fw-semibold">Run Selection</label>
                                <select name="run_number" id="run_number" class="form-select form-select-sm" onchange="loadContent()">
                                    <option value="">-- All Runs --</option>
                                    <option value="1">Run 1</option>
                                    <option value="2">Run 2</option>
                                    <option value="3">Run 3</option>
                                    <option value="4">Run 4</option>
                                    <option value="5">Run 5</option>
                                </select>
                                <small class="form-text text-muted">Filter by specific run</small>
                            </div>
                            
                            <div class="col-3">
                                <label for="gender_filter_main" class="form-label mb-1 small fw-semibold">Gender (Optional)</label>
                                <select name="gender_filter_main" id="gender_filter_main" class="form-select form-select-sm" onchange="loadContent()">
                                    <option value="all">-- All Genders --</option>
                                    <option value="M">Male</option>
                                    <option value="F">Female</option>
                                </select>
                            </div>
                            
                                <?php if ($view_type === 'summary_table' && !empty($categories)): ?>
                                    <div class="col-3">
                                        <label for="category_filter" class="form-label mb-1 small fw-semibold">Category Filter</label>
                                        <select name="category_filter" id="category_filter" class="form-select form-select-sm" onchange="loadSummaryTable()">
                                            <option value="all">-- All Categories --</option>
                                            
                                            <?php 
                                            // Track which categories have been shown to avoid duplicates
                                            $shown_categories = array();
                                            ?>
                                            
                                            <?php if ($selected_heat): ?>
                                                <optgroup label="Main Categories for Heat <?= $selected_heat ?>">
                                                    <?php foreach ($categories as $category): ?>
                                                        <?php if ($category['is_main_category']): ?>
                                                            <?php $shown_categories[] = $category['id']; ?>
                                                            <option value="<?= $category['id'] ? $category['id'] : htmlspecialchars($category['category_name']) ?>">
                                                                <?= htmlspecialchars($category['category_name']) ?>
                                                            </option>
                                                        <?php endif; ?>
                                                    <?php endforeach; ?>
                                                </optgroup>
                                            <?php endif; ?>
                                            
                                            <?php 
                                            // Check if there are ranking categories that haven't been shown yet
                                            $ranking_categories = array_filter($categories, function($c) use ($shown_categories) { 
                                                return $c['use_for_ranking'] && !in_array($c['id'], $shown_categories); 
                                            });
                                            ?>
                                            
                                            <?php if (!empty($ranking_categories)): ?>
                                                <optgroup label="Ranking Categories">
                                                    <?php foreach ($ranking_categories as $category): ?>
                                                        <?php $shown_categories[] = $category['id']; ?>
                                                        <option value="<?= $category['id'] ? $category['id'] : htmlspecialchars($category['category_name']) ?>">
                                                            <?= htmlspecialchars($category['category_name']) ?>
                                                        </option>
                                                    <?php endforeach; ?>
                                                </optgroup>
                                            <?php endif; ?>
                                            
                                            <?php 
                                            // Check if there are other categories that haven't been shown yet
                                            $other_categories = array_filter($categories, function($c) use ($shown_categories) { 
                                                return !$c['is_main_category'] && !$c['use_for_ranking'] && !in_array($c['id'], $shown_categories); 
                                            });
                                            ?>
                                            
                                            <?php if (!empty($other_categories)): ?>
                                                <optgroup label="Other Categories">
                                                    <?php foreach ($other_categories as $category): ?>
                                                        <option value="<?= $category['id'] ? $category['id'] : htmlspecialchars($category['category_name']) ?>">
                                                            <?= htmlspecialchars($category['category_name']) ?>
                                                        </option>
                                                    <?php endforeach; ?>
                                                </optgroup>
                                            <?php endif; ?>
                                        </select>
                                        
                                        <div class="form-text text-muted">
                                            <?php if ($selected_heat): ?>
                                                Showing main categories for Heat <?= $selected_heat ?> and all ranking categories
                                            <?php else: ?>
                                                Showing all main and ranking categories
                                            <?php endif; ?>
                                        </div>
                                    </div>
                                <?php endif; ?>
                            <?php endif; ?>
                         </form>
                        </div>
                    </div>

                     <?php if ($selected_event): ?>
                    
                                <!-- Content Display -->
                                    <div class="border-0 shadow-none card mt-3" id="mainContentCard">
                                        <div class="card shadow-none card-body p-2">
                                            <div class="d-flex justify-content-between align-items-center mb-2">
                                                <h6 class="mb-0 fw-bold">
                                                    <?php if ($view_type === 'summary_table'): ?>
                                                        <i class="fas fa-table me-1"></i>Summary Table Preview
                                                    <?php else: ?>
                                                        <i class="fas fa-list me-1"></i>Start List Preview
                                                    <?php endif; ?>
                                                    <?php if (!empty($selected_heats)): ?>
                                                        <?php if (count($selected_heats) === 1): ?>
                                                            - Heat <?= $selected_heats[0] ?>
                                                        <?php else: ?>
                                                            - Heats <?= implode(', ', $selected_heats) ?>
                                                        <?php endif; ?>
                                                    <?php endif; ?>
                                                </h6>


                                                    <!-- Action Buttons -->
                                                <div class="actions">
                                                    <?php if ($view_type === 'start_list'): ?>
                                                        <!-- Start List Actions -->
                                                        <div class="d-flex flex-wrap gap-2 mb-0">
                                                            <button type="button" class="btn btn-outline-secondary" onclick="refreshContent()">
                                                                <i class="fas fa-refresh me-1"></i>Refresh
                                                            </button>
                                                            <button type="button" class="btn btn-outline-primary" data-bs-toggle="collapse" data-bs-target="#columnToggles">
                                                                <i class="fas fa-columns me-1"></i>Column Options
                                                            </button>
                                                            <button type="button" class="btn btn-success btn-sm" onclick="saveCurrentConfig()">
                                                                <i class="fas fa-plus me-1"></i>Save Current Configuration
                                                            </button>
                                                        </div>
                                                    <?php else: ?>
                                                        <!-- Summary Table Actions -->
                                                        <div class="row g-2">
                                                            <div class="col-12">
                                                
                                                
                                                                <div class="d-flex flex-wrap gap-2 mb-0">
                                                                    
                                                                    <button type="button" class="btn btn-outline-secondary" onclick="refreshContent()">
                                                                        <i class="fas fa-refresh me-1"></i>Refresh
                                                                    </button>
                                                                    <button type="button" class="btn btn-outline-primary" data-bs-toggle="collapse" data-bs-target="#columnToggles">
                                                                        <i class="fas fa-columns me-1"></i>Column Options
                                                                    </button>
                                                                    <button type="button" class="btn btn-success btn-sm" onclick="saveCurrentConfig()">
                                                                        <i class="fas fa-plus me-1"></i>Save Current Configuration
                                                                    </button>
                                                                </div>
                                                            </div>
                                                
                                            
                                                        </div>
                                            
                                                    <?php endif; ?>
                                                    
                                                </div>
                                            </div>
                                                <!-- Editing Mode Banner -->
                                                    <div id="editingModeBanner" class="alert alert-warning d-none mb-2" role="alert">
                                                        <div class="d-flex justify-content-between align-items-center">
                                                            <div>
                                                                <i class="fas fa-edit me-2"></i>
                                                                <strong>Editing Configuration:</strong> <span id="editingConfigName"></span>
                                                            </div>
                                                            <div class="btn-group">
                                                                <button type="button" class="btn btn-success btn-sm" onclick="saveEditedConfiguration()">
                                                                    <i class="fas fa-save me-1"></i>Save Changes
                                                                </button>
                                                                <button type="button" class="btn btn-secondary btn-sm" onclick="cancelConfigurationEdit()">
                                                                    <i class="fas fa-times me-1"></i>Cancel
                                                                </button>
                                                            </div>
                                                        </div>
                                                    </div>
                                                    
                                                    <!-- Configuration Details Panel (shown during editing) -->
                                                    <div id="editConfigDetails" class="alert alert-info d-none mb-2" role="alert">
                                                        <h6 class="mb-2"><i class="fas fa-cog me-2"></i>Configuration Details</h6>
                                                        <div class="row g-2">
                                                            <div class="col-md-4">
                                                                <label for="editConfigName" class="form-label small fw-semibold">Configuration Name</label>
                                                                <input type="text" id="editConfigName" class="form-control form-control-sm" placeholder="Enter configuration name">
                                                            </div>
                                                            <div class="col-md-2">
                                                                <label for="editConfigStatus" class="form-label small fw-semibold">Status</label>
                                                                <select id="editConfigStatus" class="form-select form-select-sm">
                                                                    <option value="draft">Draft</option>
                                                                    <option value="active">Active</option>
                                                                    <option value="public">Public</option>
                                                                    <option value="private">Private</option>
                                                                </select>
                                                            </div>
                                                            <div class="col-md-2">
                                                                <label for="editConfigOrder" class="form-label small fw-semibold">Display Order</label>
                                                                <input type="number" id="editConfigOrder" class="form-control form-control-sm" value="0" min="0">
                                                            </div>
                                                            <div class="col-md-4">
                                                                <label for="editConfigViewType" class="form-label small fw-semibold">View Type</label>
                                                                <input type="text" id="editConfigViewType" class="form-control form-control-sm" readonly>
                                                            </div>
                                                        </div>
                                                    </div>

                                                <!-- Column Toggle Panel -->
                                            <div class="col-12 m-0 p-0">
                                                <div class="collapse" id="columnToggles">
                                                    <div class="border-0 shadow-none card card-body bg-light mt-2">
                                                        <div class="d-flex justify-content-between align-items-center mb-3">
                                                            <h6 class="mb-0"><i class="fas fa-columns me-2"></i>Column Configuration</h6>
                                                        </div>
                                                        
                                                        <!-- Tab Navigation for Column Options -->
                                                        <ul class="nav nav-pills nav-fill mb-3" id="columnConfigTabs" role="tablist">
                                                            <li class="nav-item text-primary" role="presentation">
                                                                <button class="nav-link active" id="visibility-tab" data-bs-toggle="pill" data-bs-target="#visibility-panel" type="button" role="tab">
                                                                    <i class="fas fa-eye me-1"></i>Visibility
                                                                </button>
                                                            </li>
                                                            <li class="nav-item text-primary" role="presentation">
                                                                <button class="nav-link" id="rename-tab" data-bs-toggle="pill" data-bs-target="#rename-panel" type="button" role="tab">
                                                                    <i class="fas fa-edit me-1"></i>Rename Columns
                                                                </button>
                                                            </li>
                                                        </ul>
                                                        
                                                        <!-- Tab Content -->
                                                        <div class="tab-content" id="columnConfigTabContent">
                                                            <!-- Visibility Panel -->
                                                            <div class="tab-pane fade show active" id="visibility-panel" role="tabpanel">
                                                                <div class="row g-2">
                                                                    <!-- Basic Columns -->
                                                                    <div class="col-md-3">
                                                                        <h6 class="text-muted small mb-2">Basic Info</h6>
                                                                        <div class="form-check form-switch">
                                                                            <input class="form-check-input" type="checkbox" id="showRank" checked onchange="loadContent()">
                                                                            <label class="form-check-label" for="showRank">Rank</label>
                                                                        </div>
                                                                        <div class="form-check form-switch">
                                                                            <input class="form-check-input" type="checkbox" id="showBip" checked onchange="loadContent()">
                                                                            <label class="form-check-label" for="showBip">BIB</label>
                                                                        </div>
                                                                        <div class="form-check form-switch">
                                                                            <input class="form-check-input" type="checkbox" id="showParticipant" checked onchange="loadContent()">
                                                                            <label class="form-check-label" for="showParticipant">Participant</label>
                                                                        </div>
                                                                        <div class="form-check form-switch">
                                                                            <input class="form-check-input" type="checkbox" id="showCategory" checked onchange="loadContent()">
                                                                            <label class="form-check-label" for="showCategory">Category</label>
                                                                        </div>
                                                                        <div class="form-check form-switch">
                                                                            <input class="form-check-input" type="checkbox" id="showClub" checked onchange="loadContent()">
                                                                            <label class="form-check-label" for="showClub">Club</label>
                                                                        </div>
                                                                        <div class="form-check form-switch">
                                                                            <input class="form-check-input" type="checkbox" id="showGender" checked onchange="loadContent()">
                                                                            <label class="form-check-label" for="showGender">Gender</label>
                                                                        </div>
                                                                        <div class="form-check form-switch">
                                                                            <input class="form-check-input" type="checkbox" id="showFisCode" onchange="loadContent()">
                                                                            <label class="form-check-label" for="showFisCode">FIS Code</label>
                                                                        </div>
                                                                        <div class="form-check form-switch">
                                                                            <input class="form-check-input" type="checkbox" id="showLicenceCode" onchange="loadContent()">
                                                                            <label class="form-check-label" for="showLicenceCode">Licence Code</label>
                                                                        </div>
                                                                        <div class="form-check form-switch">
                                                                            <input class="form-check-input" type="checkbox" id="showCountry" onchange="loadContent()">
                                                                            <label class="form-check-label" for="showCountry">Country Code</label>
                                                                        </div>
                                                                        <div class="form-check form-switch">
                                                                            <input class="form-check-input" type="checkbox" id="showBirthYear" onchange="loadContent()">
                                                                            <label class="form-check-label" for="showBirthYear">Birth Year</label>
                                                                        </div>
                                                                        <div class="form-check form-switch">
                                                                            <input class="form-check-input" type="checkbox" id="showAge" onchange="loadContent()">
                                                                            <label class="form-check-label" for="showAge">Age</label>
                                                                        </div>
                                                                    </div>
                                                                    
                                                                    <!-- Score Columns -->
                                                                    <div class="col-md-3">
                                                                        <h6 class="text-muted small mb-2">Score Details</h6>
                                                                        <div class="form-check form-switch">
                                                                            <input class="form-check-input" type="checkbox" id="showRuns" checked onchange="loadContent()">
                                                                            <label class="form-check-label" for="showRuns">Individual Runs</label>
                                                                        </div>
                                                                        <div class="form-check form-switch">
                                                                            <input class="form-check-input" type="checkbox" id="showJudges" onchange="loadContent()">
                                                                            <label class="form-check-label" for="showJudges">Judge Scores</label>
                                                                        </div>
                                                                        <div class="form-check form-switch">
                                                                            <input class="form-check-input" type="checkbox" id="showControlPoints" onchange="loadContent()">
                                                                            <label class="form-check-label" for="showControlPoints">Control Points</label>
                                                                        </div>
                                                                        <div class="form-check form-switch">
                                                                            <input class="form-check-input" type="checkbox" id="showFigures" onchange="loadContent()">
                                                                            <label class="form-check-label" for="showFigures">Figures</label>
                                                                        </div>
                                                                    </div>
                                                                    
                                                                    <!-- Summary Columns -->
                                                                    <div class="col-md-3">
                                                                        <h6 class="text-muted small mb-2">Heat Summary</h6>
                                                                        <div class="form-check form-switch">
                                                                            <input class="form-check-input" type="checkbox" id="showHeatBest" checked onchange="loadContent()">
                                                                            <label class="form-check-label" for="showHeatBest">Heat Best</label>
                                                                        </div>
                                                                        <div class="form-check form-switch">
                                                                            <input class="form-check-input" type="checkbox" id="showHeatAverage" onchange="loadContent()">
                                                                            <label class="form-check-label" for="showHeatAverage">Heat Average</label>
                                                                        </div>
                                                                        
                                                                        <h6 class="text-muted small mb-2 mt-3">Heat Direction</h6>
                                                                        <div class="form-check">
                                                                            <input class="form-check-input" type="radio" name="heatDirection" id="heatDirectionRow" value="row" checked onchange="loadContent()">
                                                                            <label class="form-check-label" for="heatDirectionRow">
                                                                                <small>Row (heats side by side)</small>
                                                                            </label>
                                                                        </div>
                                                                        <div class="form-check">
                                                                            <input class="form-check-input" type="radio" name="heatDirection" id="heatDirectionColumn" value="column" onchange="loadContent()">
                                                                            <label class="form-check-label" for="heatDirectionColumn">
                                                                                <small>Column (heats stacked)</small>
                                                                            </label>
                                                                        </div>
                                                                    </div>
                                                                    
                                                                    <!-- Overall Summary -->
                                                                    <div class="col-md-3">
                                                                        <h6 class="text-muted small mb-2">Overall Summary</h6>
                                                                        <div class="form-check form-switch">
                                                                            <input class="form-check-input" type="checkbox" id="showOverallBest" onchange="loadContent()">
                                                                            <label class="form-check-label" for="showOverallBest">Overall Average</label>
                                                                        </div>
                                                                        <div class="form-check form-switch">
                                                                            <input class="form-check-input" type="checkbox" id="showHighestAverage" onchange="loadContent()">
                                                                            <label class="form-check-label" for="showHighestAverage">Overall Best</label>
                                                                        </div>
                                                                    </div>
                                                                
                                                                    <!-- Additional Options -->
                                                                    <hr class="my-3">
                                                                    <div class="row g-3">
                                                                        <div class="col-md-4">
                                                                            <label for="sortBy" class="form-label small">Sort By</label>
                                                                            <select id="sortBy" class="form-select form-select-sm" onchange="loadContent()">
                                                                                <option value="sort_order" selected>Sort Order</option>
                                                                                <option value="OverallAverage">Overall Average</option>
                                                                                <option value="OverallBest">Overall Best</option>
                                                                                <option value="participant_name">Name</option>
                                                                                <option value="bib">BIB Number</option>
                                                                                <option value="category">Category</option>
                                                                                <option value="club">Club</option>
                                                                            </select>
                                                                        </div>
                                                                        <div class="col-md-4">
                                                                            <label for="sortDirection" class="form-label small">Sort Direction</label>
                                                                            <select id="sortDirection" class="form-select form-select-sm" onchange="loadContent()">
                                                                                <option value="desc">Descending (High to Low)</option>
                                                                                <option value="asc">Ascending (Low to High)</option>
                                                                            </select>
                                                                        </div>
                                                                        <div class="col-md-4">
                                                                            <label for="genderFilter" class="form-label small">Gender Filter</label>
                                                                            <select id="genderFilter" class="form-select form-select-sm" onchange="loadContent()">
                                                                                <option value="all">All Genders</option>
                                                                                <option value="M">Male</option>
                                                                                <option value="F">Female</option>
                                                                            </select>
                                                                        </div>
                                                                    </div>
                                                                
                                                                    <!-- Additional Display Options -->
                                                                    <div class="row g-3 mt-2">
                                                                        <div class="col-md-12">
                                                                            <h6 class="text-muted small mb-2">Additional Info</h6>
                                                                            <div class="form-check form-switch mb-2">
                                                                                <input class="form-check-input" type="checkbox" id="showEventSettings" onchange="toggleEventSettingsDetails(); loadContent();">
                                                                                <label class="form-check-label" for="showEventSettings">Show Event Format Settings</label>
                                                                            </div>
                                                                            
                                                                            <!-- Event Settings Detail Toggles -->
                                                                            <div class="ms-4" id="eventSettingsDetails" style="display: none;">
                                                                                <div class="row g-2">
                                                                                    <div class="col-md-6">
                                                                                        <div class="form-check form-check-sm">
                                                                                            <input class="form-check-input" type="checkbox" id="showFormatName" checked onchange="loadContent()">
                                                                                            <label class="form-check-label small" for="showFormatName">Format Name</label>
                                                                                        </div>
                                                                                        <div class="form-check form-check-sm">
                                                                                            <input class="form-check-input" type="checkbox" id="showJudgeInfo" checked onchange="loadContent()">
                                                                                            <label class="form-check-label small" for="showJudgeInfo">Judge Info</label>
                                                                                        </div>
                                                                                        <div class="form-check form-check-sm">
                                                                                            <input class="form-check-input" type="checkbox" id="showScaleInfo" checked onchange="loadContent()">
                                                                                            <label class="form-check-label small" for="showScaleInfo">Scoring Scale</label>
                                                                                        </div>
                                                                                    </div>
                                                                                    <div class="col-md-6">
                                                                                        <div class="form-check form-check-sm">
                                                                                            <input class="form-check-input" type="checkbox" id="showDropRule" checked onchange="loadContent()">
                                                                                            <label class="form-check-label small" for="showDropRule">Drop Rule</label>
                                                                                        </div>
                                                                                        <div class="form-check form-check-sm">
                                                                                            <input class="form-check-input" type="checkbox" id="showModeConfig" onchange="loadContent()">
                                                                                            <label class="form-check-label small" for="showModeConfig">Mode Config</label>
                                                                                        </div>
                                                                                        <div class="form-check form-check-sm">
                                                                                            <input class="form-check-input" type="checkbox" id="showHeatInfo" checked onchange="loadContent()">
                                                                                            <label class="form-check-label small" for="showHeatInfo">Heat Info</label>
                                                                                        </div>
                                                                                    </div>
                                                                                </div>
                                                                            </div>
                                                                            
                                                                            <div class="form-check form-switch mb-2 mt-3">
                                                                                <input class="form-check-input" type="checkbox" id="showLive" onchange="toggleLiveRefresh()">
                                                                                <label class="form-check-label" for="showLive">
                                                                                    <i class="fas fa-sync-alt me-1"></i>Enable Live Scores (Auto-refresh)
                                                                                </label>
                                                                            </div>
                                                                            <small class="text-muted ms-4">When enabled, scores will automatically update every 5 seconds</small>
                                                                        </div>
                                                                    
                                                                    </div>
                                                                </div>
                                                            </div>
                                                            
                                                            <!-- Rename Columns Panel -->
                                                            <div class="tab-pane fade" id="rename-panel" role="tabpanel">
                                                                <div class="alert alert-info mb-3">
                                                                    <i class="fas fa-info-circle me-2"></i>
                                                                    <strong>Column Renaming:</strong> Customize column headers for your event. 
                                                                    Leave blank to use system default names. Changes apply immediately and can be saved with configurations.
                                                                </div>
                                                
                                                                        <div class="row g-3">
                                                                            <!-- Basic Info Columns -->
                                                                            <div class="col-md-6">
                                                                                <div class="border rounded p-3">
                                                                                    <h6 class="text-primary mb-3"><i class="fas fa-user me-1"></i>Basic Information</h6>
                                                                                    <div class="row g-2">
                                                                                        <div class="col-6">
                                                                                            <label class="form-label small fw-semibold">Rank Column</label>
                                                                                            <input type="text" class="form-control form-control-sm" id="rename_rank" placeholder="Rank (default)">
                                                                                        </div>
                                                                                        <div class="col-6">
                                                                                            <label class="form-label small fw-semibold">BIB Column</label>
                                                                                            <input type="text" class="form-control form-control-sm" id="rename_bib" placeholder="BIB (default)">
                                                                                        </div>
                                                                                        <div class="col-6">
                                                                                            <label class="form-label small fw-semibold">Participant Column</label>
                                                                                            <input type="text" class="form-control form-control-sm" id="rename_participant" placeholder="Participant (default)">
                                                                                        </div>
                                                                                        <div class="col-6">
                                                                                            <label class="form-label small fw-semibold">Category Column</label>
                                                                                            <input type="text" class="form-control form-control-sm" id="rename_category" placeholder="Category (default)">
                                                                                        </div>
                                                                                        <div class="col-6">
                                                                                            <label class="form-label small fw-semibold">Club Column</label>
                                                                                            <input type="text" class="form-control form-control-sm" id="rename_club" placeholder="Club (default)">
                                                                                        </div>
                                                                                        <div class="col-6">
                                                                                            <label class="form-label small fw-semibold">Gender Column</label>
                                                                                            <input type="text" class="form-control form-control-sm" id="rename_gender" placeholder="Gender (default)">
                                                                                        </div>
                                                                                    </div>
                                                                                </div>
                                                                            </div>
                                                                            
                                                                            <!-- Additional Info & Score Columns -->
                                                                            <div class="col-md-6">
                                                                                <div class="border rounded p-3">
                                                                                    <h6 class="text-success mb-3"><i class="fas fa-chart-line me-1"></i>Additional Info & Scores</h6>
                                                                                    <div class="row g-2">
                                                                                        <div class="col-6">
                                                                                            <label class="form-label small fw-semibold">FIS Code Column</label>
                                                                                            <input type="text" class="form-control form-control-sm" id="rename_fis_code" placeholder="FIS Code (default)">
                                                                                        </div>
                                                                                        <div class="col-6">
                                                                                            <label class="form-label small fw-semibold">Licence Code Column</label>
                                                                                            <input type="text" class="form-control form-control-sm" id="rename_licence_code" placeholder="Licence Code (default)">
                                                                                        </div>
                                                                                        <div class="col-6">
                                                                                            <label class="form-label small fw-semibold">Country Code Column</label>
                                                                                            <input type="text" class="form-control form-control-sm" id="rename_country" placeholder="Country Code (default)">
                                                                                        </div>
                                                                                        <div class="col-6">
                                                                                            <label class="form-label small fw-semibold">Individual Runs Column</label>
                                                                                            <input type="text" class="form-control form-control-sm" id="rename_runs" placeholder="Individual Runs (default)">
                                                                                        </div>
                                                                                        <div class="col-6">
                                                                                            <label class="form-label small fw-semibold">Judge Scores Column</label>
                                                                                            <input type="text" class="form-control form-control-sm" id="rename_judges" placeholder="Judge Scores (default)">
                                                                                        </div>
                                                                                        <div class="col-6">
                                                                                            <label class="form-label small fw-semibold">Control Points Column</label>
                                                                                            <input type="text" class="form-control form-control-sm" id="rename_control_points" placeholder="Control Points (default)">
                                                                                        </div>
                                                                                        <div class="col-6">
                                                                                            <label class="form-label small fw-semibold">Figures Column</label>
                                                                                            <input type="text" class="form-control form-control-sm" id="rename_figures" placeholder="Figures (default)">
                                                                                        </div>
                                                                                    </div>
                                                                                </div>
                                                                            </div>
                                                                            
                                                                            <!-- Summary Columns -->
                                                                            <div class="col-12">
                                                                                <div class="border rounded p-3">
                                                                                    <h6 class="text-warning mb-3"><i class="fas fa-trophy me-1"></i>Summary Columns</h6>
                                                                                    <div class="row g-2">
                                                                                        <div class="col-md-3">
                                                                                            <label class="form-label small fw-semibold">Heat Best Column</label>
                                                                                            <input type="text" class="form-control form-control-sm" id="rename_heat_best" placeholder="Heat Best (default)">
                                                                                        </div>
                                                                                        <div class="col-md-3">
                                                                                            <label class="form-label small fw-semibold">Heat Average Column</label>
                                                                                            <input type="text" class="form-control form-control-sm" id="rename_heat_average" placeholder="Heat Average (default)">
                                                                                        </div>
                                                                                        <div class="col-md-3">
                                                                                            <label class="form-label small fw-semibold">Overall Average Column</label>
                                                                                            <input type="text" class="form-control form-control-sm" id="rename_overall_best" placeholder="Overall Average (default)">
                                                                                        </div>
                                                                                        <div class="col-md-3">
                                                                                            <label class="form-label small fw-semibold">Overall Best Column</label>
                                                                                            <input type="text" class="form-control form-control-sm" id="rename_highest_average" placeholder="Overall Best (default)">
                                                                                        </div>
                                                                                    </div>
                                                                                </div>
                                                                            </div>
                                                                        </div>
                                                
                                                                        <!-- Quick Actions -->
                                                                        <div class="mt-3  ">
                                                                            <div class="bg-light rounded p-3  d-flex justify-content-between align-items-center">
                                                                                <div class="m-0">
                                                                                    <small class="text-muted fw-semibold"><i class="fas fa-magic me-1"></i>Quick Actions</small>
                                                                                </div>
                                                                                
                                                                                <!-- Copy/Paste Group -->
                                                                                <div class="m-0 d-flex justify-content-between align-items-center">
                                                                                    <small class="text-muted d-block m-0">Copy/Paste:&nbsp;</small>
                                                                                    <div class="btn-group btn-group-sm" role="group">
                                                                                        <button type="button" class="btn btn-outline-primary" onclick="copyCustomNames()">
                                                                                            <i class="fas fa-copy m-0"></i>Copy
                                                                                        </button>
                                                                                        <button type="button" class="btn btn-outline-primary" onclick="pasteCustomNames()" id="pasteCustomNamesBtn" disabled>
                                                                                            <i class="fas fa-paste m-0"></i>Paste
                                                                                        </button>
                                                                                    </div>
                                                                                </div>
                                                                                
                                                                                <!-- Preset Group -->
                                                                                <div class="m-0 d-flex justify-content-between align-items-center">
                                                                                    <small class="text-muted d-block m-0">Use preset:&nbsp;</small>
                                                                                    <div class="btn-group btn-group-sm" role="group">
                                                                                        <button type="button" class="btn btn-outline-info" onclick="loadRenamePresets('ski')">
                                                                                            <i class="fas fa-skiing m-0"></i>Ski
                                                                                        </button>
                                                                                        <button type="button" class="btn btn-outline-info" onclick="loadRenamePresets('snowboard')">
                                                                                            <i class="fas fa-snowboarding m-0"></i>Board
                                                                                        </button>
                                                                                        <button type="button" class="btn btn-outline-info" onclick="loadRenamePresets('generic')">
                                                                                            <i class="fas fa-table m-0"></i>Generic
                                                                                        </button>
                                                                                    </div>
                                                                                </div>
                                                                                
                                                                                <!-- Action Buttons -->
                                                                                <div class=" d-flex justify-content-between align-items-center">
                                                                                <div class="d-flex justify-content-between align-items-center">
                                                                                    <button type="button" class="btn btn-outline-secondary btn-sm" onclick="clearAllRenames()">
                                                                                        <i class="fas fa-eraser me-1"></i>Clear All
                                                                                    </button>
                                                                                    <button type="button" class="btn btn-success btn-sm" onclick="applyColumnRenames()">
                                                                                        <i class="fas fa-check me-1"></i>Apply Changes
                                                                                    </button>
                                                                                </div>  </div>
                                                                                    </div>
                                                                                </div>
                                                                            </div>
                                                                        </div>
                                                                        
                                            
                                                    </div>
                                                </div>
                                            </div>
                                        
                                         <!-- Content Display Area -->
                                        <div class="card shadow-none card-body p-2">
                                            <div id="contentDisplay">
                                                <div class="text-center p-2">
                                                    <div class="spinner-border text-primary" role="status">
                                                        <span class="visually-hidden">Loading...</span>
                                                    </div>
                                                    <p class="mt-2 text-muted">Loading content...</p>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                    </div>
                            </div>
                    </div>
                    <?php else: ?>
                    <div class="border-0 shadow-none card">
                        <div class="card shadow-none card-body text-center py-3">
                            <?php if ($view_type === 'summary_table'): ?>
                                <i class="fas fa-table fa-2x text-muted mb-2"></i>
                                <h6 class="text-muted">Select an Event</h6>
                                <p class="text-muted small mb-0">Choose an event from the dropdown above to view its summary table</p>
                            <?php else: ?>
                                <i class="fas fa-list-ol fa-2x text-muted mb-2"></i>
                                <h6 class="text-muted">Select an Event</h6>
                                <p class="text-muted small mb-0">Choose an event from the dropdown above to view its start list</p>
                            <?php endif; ?>
                        </div>
                    </div>
                <?php endif; ?>
                </div>
                                    </div>
                                
                                
                                </div>
                <!-- Two Column Layout -->
                <div class="row">
                    <!-- Left Column: Filters & Configuration Management -->
                    <div class="col-lg-3 px-2">
                        
                
                
               
                
            </div>
            <!-- End Left Column -->
            
            <!-- Right Column - Content Display -->
            <div class="col-lg-9 px-2">
               
            </div>
        </div>
    </div>
    
    <!-- Edit Configuration Modal (HIDDEN - using main UI editing now) -->
    <div class="modal fade d-none" id="editConfigModal" tabindex="-1" aria-hidden="true">
      <div class="modal-dialog modal-lg modal-dialog-scrollable">
        <div class="modal-content">
          <div class="modal-header">
            <h5 class="modal-title"><i class="fas fa-edit me-2"></i>Edit Configuration</h5>
            <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
          </div>
          <div class="modal-body">
            <div id="editConfigAlert" class="alert alert-danger d-none mb-3"></div>
            <div class="row g-3">
              <div class="col-md-6">
                <label for="editConfigName" class="form-label">Name</label>
                <input type="text" id="editConfigName" class="form-control" />
              </div>
              <div class="col-md-3">
                <label for="editConfigStatus" class="form-label">Status</label>
                <select id="editConfigStatus" class="form-select">
                  <option value="draft">Draft</option>
                  <option value="active">Active</option>
                  <option value="public">Public</option>
                  <option value="private">Private</option>
                </select>
              </div>
              <div class="col-md-3">
                <label for="editConfigOrder" class="form-label">Display Order</label>
                <input type="number" id="editConfigOrder" class="form-control" value="0" min="0" />
              </div>

              <div class="col-md-4">
                <label for="editConfigViewType" class="form-label">View Type</label>
                <input type="text" id="editConfigViewType" class="form-control" readonly />
              </div>
              <div class="col-md-4">
                <label for="editConfigHeat" class="form-label">Heat (Optional)</label>
                <select id="editConfigHeat" class="form-select">
                  <option value="">-- All Heats --</option>
                  <?php foreach ($heats as $heat): ?>
                    <option value="<?= (int)$heat['heat_number'] ?>">
                      Heat <?= (int)$heat['heat_number'] ?><?= $heat['heat_name'] ? ' - ' . htmlspecialchars($heat['heat_name']) : '' ?>
                    </option>
                  <?php endforeach; ?>
                </select>
              </div>
              <div class="col-md-4">
                <label for="editConfigCategory" class="form-label">Category (Optional)</label>
                <select id="editConfigCategory" class="form-select">
                
                <option value="all">-- All Categories --</option>
        <?php foreach ($categories as $category): ?>
            <option value="<?= $category['id'] ? $category['id'] : htmlspecialchars($category['category_name']) ?>">
                <?= htmlspecialchars($category['category_name']) ?>
                <?php if ($category['is_main_category']): ?> (Main)<?php endif; ?>
                <?php if ($category['use_for_ranking']): ?> (Ranking)<?php endif; ?>
            </option>
        <?php endforeach; ?>
                </select>
              </div>

              <div class="col-12">
                <label for="editConfigFilters" class="form-label">Filters JSON</label>
                <textarea id="editConfigFilters" class="form-control" rows="10" spellcheck="false" placeholder='{"showRuns":true,"sortBy":"OverallAverage","sortDirection":"desc"}'></textarea>
                <div class="form-text">Edit advanced options as JSON. Invalid JSON will be rejected.</div>
              </div>
            </div>
          </div>
          <div class="modal-footer">
            <button id="editConfigSaveBtn" type="button" class="btn btn-success" onclick="updateConfigurationSave()">
              <i class="fas fa-save me-1"></i>Save Changes
            </button>
            <button type="button" class="btn btn-outline-secondary" data-bs-dismiss="modal">Close</button>
          </div>
        </div>
      </div>
    </div>

    <!-- Column Rename Modal -->
    <div class="modal fade" id="columnRenameModal" tabindex="-1" aria-hidden="true">
      <div class="modal-dialog modal-lg modal-dialog-scrollable">
        <div class="modal-content">
          <div class="modal-header">
            <h5 class="modal-title"><i class="fas fa-edit me-2"></i>Rename Table Columns</h5>
            <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
          </div>
          <div class="modal-body">
            <div class="alert alert-info">
                <i class="fas fa-info-circle me-2"></i>
                <strong>Column Renaming:</strong> Customize column headers for your event or heat. 
                Leave blank to use system default names. Changes apply to current view and can be saved with configurations.
            </div>
            
            <div class="row g-4">
                <!-- Basic Info Columns -->
                <div class="col-md-6 col-lg-4">
                    <div class="card shadow-none card border-primary">
                        <div class="border-0 shadow-none card-body p-2">
                            <h6 class="mb-2 text-primary fw-bold"><i class="fas fa-user me-1"></i>Basic Information</h6>
                            <div class="mb-2">
                                <label class="form-label mb-1 small fw-bold">Rank Column</label>
                                <input type="text" class="form-control form-control-sm" id="rename_rank" placeholder="Rank (default)">
                            </div>
                            <div class="mb-2">
                                <label class="form-label mb-1 small fw-bold">BIB Column</label>
                                <input type="text" class="form-control form-control-sm" id="rename_bib" placeholder="BIB (default)">
                            </div>
                            <div class="mb-2">
                                <label class="form-label mb-1 small fw-bold">Participant Column</label>
                                <input type="text" class="form-control form-control-sm" id="rename_participant" placeholder="Participant (default)">
                            </div>
                            <div class="mb-3">
                                <label class="form-label small fw-bold">Category Column</label>
                                <input type="text" class="form-control form-control-sm" id="rename_category" placeholder="Category (default)">
                            </div>
                            <div class="mb-3">
                                <label class="form-label small fw-bold">Club Column</label>
                                <input type="text" class="form-control form-control-sm" id="rename_club" placeholder="Club (default)">
                            </div>
                            <div class="mb-0">
                                <label class="form-label small fw-bold">Gender Column</label>
                                <input type="text" class="form-control form-control-sm" id="rename_gender" placeholder="Gender (default)">
                            </div>
                        </div>
                    </div>
                </div>
                
                <!-- Additional Info Columns -->
                <div class="col-md-6 col-lg-4">
                    <div class="card shadow-none card border-secondary">
                        <div class="border-0 shadow-none card-header bg-info text-white">
                            <h6 class="mb-0"><i class="fas fa-id-card me-2"></i>Additional Info</h6>
                        </div>
                        <div class="border-0 shadow-none card-body p-3">
                            <div class="mb-3">
                                <label class="form-label small fw-bold">FIS Code Column</label>
                                <input type="text" class="form-control form-control-sm" id="rename_fis_code" placeholder="FIS Code (default)">
                            </div>
                            <div class="mb-3">
                                <label class="form-label small fw-bold">Licence Code Column</label>
                                <input type="text" class="form-control form-control-sm" id="rename_licence_code" placeholder="Licence Code (default)">
                            </div>
                            <div class="mb-0">
                                <label class="form-label small fw-bold">Country Code Column</label>
                                <input type="text" class="form-control form-control-sm" id="rename_country" placeholder="Country Code (default)">
                            </div>
                        </div>
                    </div>
                </div>
                
                <!-- Score Columns -->
                <div class="col-md-6 col-lg-4">
                    <div class="card shadow-none card border-success">
                        <div class="border-0 shadow-none card-header bg-success text-white">
                            <h6 class="mb-0"><i class="fas fa-chart-line me-2"></i>Score Details</h6>
                        </div>
                        <div class="border-0 shadow-none card-body p-3">
                            <div class="mb-3">
                                <label class="form-label small fw-bold">Individual Runs Column</label>
                                <input type="text" class="form-control form-control-sm" id="rename_runs" placeholder="Individual Runs (default)">
                            </div>
                            <div class="mb-3">
                                <label class="form-label small fw-bold">Judge Scores Column</label>
                                <input type="text" class="form-control form-control-sm" id="rename_judges" placeholder="Judge Scores (default)">
                            </div>
                            <div class="mb-3">
                                <label class="form-label small fw-bold">Control Points Column</label>
                                <input type="text" class="form-control form-control-sm" id="rename_control_points" placeholder="Control Points (default)">
                            </div>
                            <div class="mb-0">
                                <label class="form-label small fw-bold">Figures Column</label>
                                <input type="text" class="form-control form-control-sm" id="rename_figures" placeholder="Figures (default)">
                            </div>
                        </div>
                    </div>
                </div>
                
                <!-- Heat Summary Columns -->
                <div class="col-md-6 col-lg-6">
                    <div class="card shadow-none card border-warning">
                        <div class="border-0 shadow-none card-header bg-warning text-dark">
                            <h6 class="mb-0"><i class="fas fa-fire me-2"></i>Heat Summary</h6>
                        </div>
                        <div class="border-0 shadow-none card-body p-3">
                            <div class="mb-3">
                                <label class="form-label small fw-bold">Heat Best Column</label>
                                <input type="text" class="form-control form-control-sm" id="rename_heat_best" placeholder="Heat Best (default)">
                            </div>
                            <div class="mb-0">
                                <label class="form-label small fw-bold">Heat Average Column</label>
                                <input type="text" class="form-control form-control-sm" id="rename_heat_average" placeholder="Heat Average (default)">
                            </div>
                        </div>
                    </div>
                </div>
                
                <!-- Overall Summary Columns -->
                <div class="col-md-6 col-lg-6">
                    <div class="card shadow-none card border-danger">
                        <div class="border-0 shadow-none card-header bg-danger text-white">
                            <h6 class="mb-0"><i class="fas fa-trophy me-2"></i>Overall Summary</h6>
                        </div>
                        <div class="border-0 shadow-none card-body p-3">
                            <div class="mb-3">
                                <label class="form-label small fw-bold">Overall Average Column</label>
                                <input type="text" class="form-control form-control-sm" id="rename_overall_best" placeholder="Overall Average (default)">
                            </div>
                            <div class="mb-0">
                                <label class="form-label small fw-bold">Overall Best Column</label>
                                <input type="text" class="form-control form-control-sm" id="rename_highest_average" placeholder="Overall Best (default)">
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            
            <!-- Quick Actions -->
            <div class="mt-4">
                <div class="card shadow-none card bg-light">
                    <div class="border-0 shadow-none card-body">
                        <h6 class="card-title"><i class="fas fa-magic me-2"></i>Quick Actions</h6>
                        <div class="btn-group" role="group">
                            <button type="button" class="btn btn-sm btn-outline-secondary" onclick="clearAllRenames()">
                                <i class="fas fa-eraser me-1"></i>Clear All
                            </button>
                            <button type="button" class="btn btn-sm btn-outline-info" onclick="loadRenamePresets('ski')">
                                <i class="fas fa-skiing me-1"></i>Ski Preset
                            </button>
                            <button type="button" class="btn btn-sm btn-outline-info" onclick="loadRenamePresets('snowboard')">
                                <i class="fas fa-snowboarding me-1"></i>Snowboard Preset
                            </button>
                            <button type="button" class="btn btn-sm btn-outline-info" onclick="loadRenamePresets('generic')">
                                <i class="fas fa-table me-1"></i>Generic Sports
                            </button>
                        </div>
                    </div>
                </div>
            </div>
          </div>
          <div class="modal-footer">
            <div class="me-auto">
                <small class="text-muted">
                    <i class="fas fa-info-circle me-1"></i>Changes are applied immediately and can be saved with configurations
                </small>
            </div>
            <button type="button" class="btn btn-success" onclick="applyColumnRenames()">
                <i class="fas fa-check me-1"></i>Apply Renames
            </button>
            <button type="button" class="btn btn-outline-secondary" data-bs-dismiss="modal">Cancel</button>
          </div>
        </div>
      </div>
    </div>
    
            </div>
            <!-- End Right Column -->
        </div>
        <!-- End Main Row -->
    </div>
    <!-- End Container -->

    <!-- Save Configuration Modal -->
    <div class="modal fade" id="saveConfigModal" tabindex="-1" aria-hidden="true">
      <div class="modal-dialog modal-lg modal-dialog-scrollable">
        <div class="modal-content">
          <div class="modal-header">
            <h5 class="modal-title"><i class="fas fa-save me-2"></i>Save Configuration</h5>
            <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
          </div>
          <div class="modal-body">
            <div class="alert alert-info">
                <i class="fas fa-info-circle me-2"></i>
                <strong>Save Current Configuration:</strong> This will save all current column visibility, filter settings, and display preferences.
            </div>
            
            <div id="saveConfigDetails" class="alert alert-info mb-3" role="alert">
                <h6 class="mb-2"><i class="fas fa-cog me-2"></i>Configuration Details</h6>
                <div class="row g-2">
                    <div class="col-md-4">
                        <label for="saveConfigName" class="form-label small fw-semibold">Configuration Name</label>
                        <input type="text" id="saveConfigName" class="form-control form-control-sm" placeholder="Enter configuration name">
                        <div class="form-text" id="suggestedName"></div>
                    </div>
                    <div class="col-md-2">
                        <label for="saveConfigStatus" class="form-label small fw-semibold">Status</label>
                        <select id="saveConfigStatus" class="form-select form-select-sm">
                            <option value="draft">Draft</option>
                            <option value="active" selected>Active</option>
                            <option value="public">Public</option>
                            <option value="private">Private</option>
                        </select>
                    </div>
                    <div class="col-md-2">
                        <label for="saveConfigOrder" class="form-label small fw-semibold">Display Order</label>
                        <input type="number" id="saveConfigOrder" class="form-control form-control-sm" value="0" min="0">
                    </div>
                    <div class="col-md-4">
                        <label for="saveConfigViewType" class="form-label small fw-semibold">View Type</label>
                        <input type="text" id="saveConfigViewType" class="form-control form-control-sm" readonly>
                    </div>
                </div>
            </div>
          </div>
          <div class="modal-footer">
            <div class="me-auto">
                <small class="text-muted">
                    <i class="fas fa-info-circle me-1"></i>This will save all current display settings and filters
                </small>
            </div>
            <button type="button" class="btn btn-success" onclick="saveConfigurationFromModal()">
                <i class="fas fa-save me-1"></i>Save Configuration
            </button>
            <button type="button" class="btn btn-outline-secondary" data-bs-dismiss="modal">Cancel</button>
          </div>
        </div>
      </div>
    </div>

    <script>
        const currentViewType = '<?= $view_type ?>';
        
        // Load content on page load if event is selected
        document.addEventListener('DOMContentLoaded', function() {
            // Load saved column renames for this event
            const saved = localStorage.getItem('columnRenames_' + <?= json_encode($selected_event) ?>);
            if (saved) {
                currentColumnRenames = JSON.parse(saved);
                // Apply the loaded renames to the UI inputs
                setTimeout(() => applyRenamesToModal(), 100);
            }
            
            <?php if ($selected_event): ?>
                loadContent();
            <?php endif; ?>
            
            // Add event listener for when the rename tab is shown
            document.addEventListener('shown.bs.tab', function(event) {
                if (event.target.id === 'rename-tab') {
                    // Load current renames when the rename tab is shown
                    applyRenamesToModal();
                }
            });
        });
        
        function switchView(viewType) {
            const url = new URL(window.location);
            url.searchParams.set('view_type', viewType);
            window.location.href = url.toString();
        }
        
        function handleEventChange() {
            const eventId = document.getElementById('event_id').value;
            
            if (!eventId) {
                // If no event selected, just update URL and reload
                const url = new URL(window.location);
                url.searchParams.delete('event_id');
                url.searchParams.delete('heat_number');
                window.location.href = url.toString();
                return;
            }
            
            // Update URL and redirect to reload heats and categories
            const url = new URL(window.location);
            url.searchParams.set('event_id', eventId);
            url.searchParams.delete('heat_number'); // Reset heat selection when changing events
            window.location.href = url.toString();
        }
        
        function handleHeatChange() {
            const eventId = <?= json_encode($selected_event) ?>;
            const heatSelect = document.getElementById('heat_number');
            const selectedHeats = Array.from(heatSelect.selectedOptions)
                .map(option => option.value)
                .filter(value => value !== ''); // Remove empty "All Heats" option
            
            console.log('Heats changed to:', selectedHeats, 'for event:', eventId);
            
            if (!eventId) {
                console.warn('No event selected');
                return;
            }
            
            // Show loading indicator
            const contentDisplay = document.getElementById('contentDisplay');
            if (contentDisplay) {
                contentDisplay.innerHTML = `
                    <div class="text-center py-4">
                        <div class="spinner-border text-primary" role="status">
                            <span class="visually-hidden">Loading...</span>
                        </div>
                        <p class="mt-2 text-muted">Loading heat data...</p>
                    </div>
                `;
            }
            
            // Update URL without page refresh
            const url = new URL(window.location);
            if (selectedHeats.length > 0) {
                url.searchParams.set('heat_number', selectedHeats.join(','));
            } else {
                url.searchParams.delete('heat_number');
            }
            window.history.pushState({}, '', url);
            
            // Update categories for the selected heats (using first heat for category filtering)
            const primaryHeat = selectedHeats.length > 0 ? selectedHeats[0] : null;
            updateCategoriesForHeat(eventId, primaryHeat);
            
            // Reload content with new heat selection
            loadContent();
            
            // Update configuration name if in editing mode
            if (typeof generateConfigName === 'function') {
                generateConfigName();
            }
        }
        
        function updateCategoriesForHeat(eventId, heatNumber) {
            const categorySelect = document.getElementById('category_filter');
            if (!categorySelect) {
                console.warn('Category filter not found');
                return;
            }
            
            console.log('Updating categories for event:', eventId, 'heat:', heatNumber);
            
            // Show loading state
            const currentValue = categorySelect.value;
            categorySelect.innerHTML = '<option value="all">Loading categories...</option>';
            categorySelect.disabled = true;
            
            // Fetch categories for the selected heat
            let url = `../api/heat_categories_api.php?event_id=${eventId}`;
            if (heatNumber && heatNumber !== '') {
                url += `&heat_number=${heatNumber}`;
            }
            
            fetch(url)
                .then(response => {
                    if (!response.ok) {
                        throw new Error(`HTTP error! status: ${response.status}`);
                    }
                    return response.json();
                })
                .then(data => {
                    console.log('Categories API response:', data);
                    
                    if (data.success) {
                        // Clear existing options
                        categorySelect.innerHTML = '';
                        
                        // Add "All Categories" option
                        const allOption = document.createElement('option');
                        allOption.value = 'all';
                        allOption.textContent = '-- All Categories --';
                        categorySelect.appendChild(allOption);
                        
                        // Add category options
                        if (data.categories && data.categories.length > 0) {
                            data.categories.forEach(category => {
                                const option = document.createElement('option');
                                option.value = category.category_name || category;
                                option.textContent = category.category_name || category;
                                categorySelect.appendChild(option);
                            });
                            console.log(`Added ${data.categories.length} categories`);
                        } else {
                            console.log('No categories found for this heat');
                        }
                        
                        // Restore previous selection if it still exists
                        if (currentValue && categorySelect.querySelector(`option[value="${currentValue}"]`)) {
                            categorySelect.value = currentValue;
                            console.log('Restored previous category selection:', currentValue);
                        } else {
                            categorySelect.value = 'all';
                            console.log('Reset to "All Categories"');
                        }
                    } else {
                        console.error('Failed to load categories:', data.message);
                        categorySelect.innerHTML = '<option value="all">-- All Categories --</option>';
                    }
                })
                .catch(error => {
                    console.error('Error fetching categories:', error);
                    categorySelect.innerHTML = '<option value="all">-- All Categories --</option>';
                })
                .finally(() => {
                    categorySelect.disabled = false;
                    console.log('Category loading completed');
                });
        }
        
        function loadContent() {
            // Skip if we're in the middle of loading a configuration
            if (window.isLoadingConfiguration) {
                console.log('Skipping loadContent - configuration is being loaded');
                return;
            }
            
            console.log('Loading content for view type:', currentViewType);
            
            if (currentViewType === 'summary_table') {
                loadSummaryTable();
            } else {
                loadStartList();
            }
        }
        
        function loadStartList() {
            const eventId = <?= json_encode($selected_event) ?>;
            const heatSelect = document.getElementById('heat_number');
            const selectedHeats = heatSelect ? Array.from(heatSelect.selectedOptions)
                .map(option => option.value)
                .filter(value => value !== '') : [];
            const genderFilter = document.getElementById('gender_filter_main')?.value ?? 'all';
            const categoryFilter = document.getElementById('category_filter')?.value ?? 'all';
            
            console.log('Loading start list with heats:', selectedHeats);
            
            if (!eventId) return;
            
            // Basic columns visibility
            const showRank = document.getElementById('showRank')?.checked ?? true;
            const showBip = document.getElementById('showBip')?.checked ?? true;
            const showParticipant = document.getElementById('showParticipant')?.checked ?? true;
            const showCategory = document.getElementById('showCategory')?.checked ?? true;
            const showClub = document.getElementById('showClub')?.checked ?? true;
            const showGender = document.getElementById('showGender')?.checked ?? true;
            const showFisCode = document.getElementById('showFisCode')?.checked ?? false;
            const showLicenceCode = document.getElementById('showLicenceCode')?.checked ?? false;
            const showCountry = document.getElementById('showCountry')?.checked ?? false;
            const showBirthYear = document.getElementById('showBirthYear')?.checked ?? false;
            const showAge = document.getElementById('showAge')?.checked ?? false;
            
            // Score columns visibility  
            const showRuns = document.getElementById('showRuns')?.checked ?? true;
            const showJudges = document.getElementById('showJudges')?.checked ?? false;
            const showControlPoints = document.getElementById('showControlPoints')?.checked ?? false;
            const showFigures = document.getElementById('showFigures')?.checked ?? false;
            
            // Sorting options
            const sortBy = document.getElementById('sortBy')?.value ?? 'sort_order';
            const sortDirection = document.getElementById('sortDirection')?.value ?? 'asc';
            const genderFilterOption = document.getElementById('genderFilter')?.value ?? 'all';
            
            let url = `../api/start_list_api.php?event_id=${eventId}&format=html`;
            
            // Add heat filters if specific heats selected
            if (selectedHeats.length > 0) {
                url += `&heat_numbers=${selectedHeats.join(',')}`;
            }
            
            // Add gender filter
            if (genderFilter && genderFilter !== 'all') {
                url += `&gender=${genderFilter}`;
            }
            
            // Add category filter
            if (categoryFilter && categoryFilter !== 'all') {
                url += `&category=${categoryFilter}`;
            }
            
            // Add column visibility parameters
            url += `&show_rank=${showRank}`;
            url += `&show_bib=${showBip}`;
            url += `&show_participant=${showParticipant}`;
            url += `&show_category=${showCategory}`;
            url += `&show_club=${showClub}`;
            url += `&show_gender=${showGender}`;
            url += `&show_fis_code=${showFisCode}`;
            url += `&show_licence_code=${showLicenceCode}`;
            url += `&show_country=${showCountry}`;
            url += `&show_birth_year=${showBirthYear}`;
            url += `&show_age=${showAge}`;
            url += `&show_runs=${showRuns}`;
            url += `&show_judges=${showJudges}`;
            url += `&show_control_points=${showControlPoints}`;
            url += `&show_figures=${showFigures}`;
            
            // Add sorting parameters
            url += `&sort=${sortBy}`;
            url += `&sort_direction=${sortDirection}`;
            url += `&gender_filter=${genderFilterOption}`;
            
            // Add column renames if they exist
            if (currentColumnRenames && Object.keys(currentColumnRenames).length > 0) {
                for (const [columnKey, customName] of Object.entries(currentColumnRenames)) {
                    if (customName && customName.trim()) {
                        url += `&rename_${columnKey}=${encodeURIComponent(customName)}`;
                    }
                }
            }
            
            fetch(url)
                .then(response => response.text())
                .then(html => {
                    // Wrap tables with table-responsive for start lists
                    let processedHtml = html;
                    if (processedHtml.includes('<table')) {
                        // Add table-responsive wrapper around tables with table-striped table-hover classes
                        processedHtml = processedHtml.replace(
                            /<table([^>]*class="[^"]*table table-striped table-hover[^"]*"[^>]*)>/g,
                            '<div class="table-responsive"><table$1>'
                        );
                        // Close the table-responsive div after the table
                        processedHtml = processedHtml.replace(
                            /<\/table>/g,
                            '</table></div>'
                        );
                    }
                    document.getElementById('contentDisplay').innerHTML = processedHtml;
                })
                .catch(error => {
                    document.getElementById('contentDisplay').innerHTML = `
                        <div class="alert alert-danger">
                            <i class="fas fa-exclamation-triangle me-2"></i>
                            Error loading start list: ${error.message}
                        </div>
                    `;
                });
        }
        
        function loadSummaryTable() {
            const eventId = <?= json_encode($selected_event) ?>;
            const heatSelect = document.getElementById('heat_number');
            const selectedHeats = heatSelect ? Array.from(heatSelect.selectedOptions)
                .map(option => option.value)
                .filter(value => value !== '') : [];
            const heatNumber = selectedHeats.join(',');
            const runNumber = document.getElementById('run_number')?.value || '';
            
            console.log('🟢 loadSummaryTable() - Event:', eventId, 'Heats:', heatNumber, selectedHeats, 'Run:', runNumber);
            
            if (!eventId) {
                console.warn('❌ No event ID - exiting');
                return;
            }
            
            // Get all column visibility settings
            const showRank = document.getElementById('showRank')?.checked ?? true;
            const showBip = document.getElementById('showBip')?.checked ?? true;
            const showParticipant = document.getElementById('showParticipant')?.checked ?? true;
            const showCategory = document.getElementById('showCategory')?.checked ?? true;
            const showClub = document.getElementById('showClub')?.checked ?? true;
            const showGender = document.getElementById('showGender')?.checked ?? true;
            const showFisCode = document.getElementById('showFisCode')?.checked ?? false;
            const showLicenceCode = document.getElementById('showLicenceCode')?.checked ?? false;
            const showCountry = document.getElementById('showCountry')?.checked ?? false;
            const showBirthYear = document.getElementById('showBirthYear')?.checked ?? false;
            const showAge = document.getElementById('showAge')?.checked ?? false;
            const showRuns = document.getElementById('showRuns')?.checked ?? true;
            const showJudges = document.getElementById('showJudges')?.checked ?? false;
            const showControlPoints = document.getElementById('showControlPoints')?.checked ?? false;
            const showFigures = document.getElementById('showFigures')?.checked ?? false;
            const showEventSettings = document.getElementById('showEventSettings')?.checked ?? false;
            const showFormatName = document.getElementById('showFormatName')?.checked ?? true;
            const showJudgeInfo = document.getElementById('showJudgeInfo')?.checked ?? true;
            const showScaleInfo = document.getElementById('showScaleInfo')?.checked ?? true;
            const showDropRule = document.getElementById('showDropRule')?.checked ?? true;
            const showModeConfig = document.getElementById('showModeConfig')?.checked ?? false;
            const showHeatInfo = document.getElementById('showHeatInfo')?.checked ?? true;
            const showHeatBest = document.getElementById('showHeatBest')?.checked ?? true;
            const showHeatAverage = document.getElementById('showHeatAverage')?.checked ?? false;
            const showOverallBest = document.getElementById('showOverallBest')?.checked ?? false;
            const showHighestAverage = document.getElementById('showHighestAverage')?.checked ?? false;
            const heatDirection = document.querySelector('input[name="heatDirection"]:checked')?.value ?? 'row';
            const sortBy = document.getElementById('sortBy')?.value ?? 'OverallAverage';
            const sortDirection = document.getElementById('sortDirection')?.value ?? 'desc';
            const genderFilter = document.getElementById('genderFilter')?.value ?? 'all';
            const categoryFilter = document.getElementById('category_filter')?.value ?? 'all';
            
            // Build URL - request HTML format from API
            let url = `../api/summary_table_api.php?event_id=${eventId}&format=html&styling=partial`;
            
            // Category filter
            if (categoryFilter && categoryFilter !== 'all') {
                url += `&category=${encodeURIComponent(categoryFilter)}`;
            }
            
            // Heat and run filter
            if (selectedHeats.length > 0) {
                const heatRunFilter = {};
                selectedHeats.forEach(heat => {
                    heatRunFilter[heat] = runNumber ? [parseInt(runNumber)] : [1, 2, 3, 4, 5];
                });
                url += `&heat_run_filter=${encodeURIComponent(JSON.stringify(heatRunFilter))}`;
            }
            
            // Column visibility
            url += `&show_rank=${showRank}&show_bib=${showBip}&show_participant=${showParticipant}`;
            url += `&show_category=${showCategory}&show_club=${showClub}&show_gender=${showGender}`;
            url += `&show_fis_code=${showFisCode}&show_licence_code=${showLicenceCode}&show_country=${showCountry}`;
            url += `&show_birth_year=${showBirthYear}&show_age=${showAge}`;
            url += `&show_runs=${showRuns}&show_judges=${showJudges}&show_control_points=${showControlPoints}`;
            url += `&show_figures=${showFigures}&show_event_settings=${showEventSettings}`;
            
            if (showEventSettings) {
                url += `&show_format_name=${showFormatName}&show_judge_info=${showJudgeInfo}`;
                url += `&show_scale_info=${showScaleInfo}&show_drop_rule=${showDropRule}`;
                url += `&show_mode_config=${showModeConfig}&show_heat_info=${showHeatInfo}`;
            }
            
            url += `&show_heat_best=${showHeatBest}&show_heat_average=${showHeatAverage}`;
            url += `&show_overall_best=${showOverallBest}&show_highest_average=${showHighestAverage}`;
            url += `&heat_direction=${heatDirection}&sort=${sortBy}&sort_direction=${sortDirection}&gender=${genderFilter}`;
            
            // Column renames
            if (currentColumnRenames && Object.keys(currentColumnRenames).length > 0) {
                for (const [columnKey, customName] of Object.entries(currentColumnRenames)) {
                    url += `&rename_${columnKey}=${encodeURIComponent(customName)}`;
                }
            }
            
            console.log('🌐 Fetching HTML from:', url);
            
            fetch(url)
                .then(response => {
                    console.log('📥 Response received, status:', response.status);
                    if (!response.ok) {
                        throw new Error(`HTTP ${response.status}`);
                    }
                    return response.text();
                })
                .then(html => {
                    console.log('✅ HTML received, length:', html.length);
                    document.getElementById('contentDisplay').innerHTML = html;
                    console.log('✅ HTML injected into contentDisplay');
                })
                .catch(error => {
                    console.error('❌ Error loading summary table:', error);
                    document.getElementById('contentDisplay').innerHTML = `
                        <div class="alert alert-danger">
                            <i class="fas fa-exclamation-triangle me-2"></i>
                            Error loading summary table: ${error.message}
                        </div>
                    `;
                });
        }
        
        // Helper function to display single table
        function displaySingleSummaryTable(data) {
            // Apply consistent styling to summary table (same as start list)
            let styledTableHead = data.table_head;
            let styledTableBody = data.table_body;
            
            // Apply start list styling classes
            if (styledTableHead) {
                styledTableHead = styledTableHead.replace(
                    /<table[^>]*>/g, 
                    '<table class="table table-striped table-hover">'
                );
            }
            
            // Display the summary table
            const tableContent = `
                <div class="summary-table-section">
                    <div class="summary-header mb-3">
                        <div class="d-flex justify-content-between align-items-center">
                            <h5 class="mb-0">Summary Results</h5>
                            <div class="summary-stats">
                                <span class="badge bg-primary me-2">${data.participant_count || 0} Participants</span>
                                ${data.is_grouped ? '<span class="badge bg-info">Grouped by Category</span>' : ''}
                            </div>
                        </div>
                        ${data.filter_summary ? `<small class="text-muted">${data.filter_summary}</small>` : ''}
                    </div>
                    <div class="table-responsive">
                        <style>${data.table_badge_colors || ''}</style>
                        <table class="table table-striped table-hover">
                            ${styledTableHead || ''}
                            ${styledTableBody || ''}
                        </table>
                    </div>
                </div>
            `;
            document.getElementById('contentDisplay').innerHTML = tableContent;
        }
        
        // Display all results grouped by heat and run when no heat is selected
        async function displayAllResultsGrouped(eventId, categoryFilter, sortBy, sortDirection) {
            try {
                // First, fetch all heats for this event
                const heatsResponse = await fetch(`heat_management_api.php?action=get_heats&event_id=${eventId}`);
                const heatsData = await heatsResponse.json();
                
                if (!heatsData.success || !heatsData.heats || heatsData.heats.length === 0) {
                    document.getElementById('contentDisplay').innerHTML = `
                        <div class="alert alert-info">
                            <i class="fas fa-info-circle me-2"></i>No heats configured for this event
                        </div>
                    `;
                    return;
                }
                
                let allTablesHTML = '<div class="all-results-view">';
                allTablesHTML += `
                    <div class="alert alert-primary mb-4">
                        <i class="fas fa-table me-2"></i>
                        <strong>All Results View</strong> - Showing all heats and runs for this event
                    </div>
                `;
                
                // Loop through each heat
                for (const heat of heatsData.heats) {
                    const heatNum = heat.heat_number;
                    const heatName = heat.heat_name || `Heat ${heatNum}`;
                    const runsCount = heat.runs_count || 3;
                    
                    // Build runs array based on runs_count
                    const runsArray = Array.from({length: runsCount}, (_, i) => i + 1);
                    const heatRunFilter = {};
                    heatRunFilter[heatNum] = runsArray;
                    
                    // Fetch results for this heat with ALL runs
                    let url = `../api/summary_table_api.php?event_id=${eventId}`;
                    url += `&heat_numbers=${heatNum}`;
                    url += `&heat_run_filter=${encodeURIComponent(JSON.stringify(heatRunFilter))}`;
                    url += `&category=${encodeURIComponent(categoryFilter || 'all')}`;
                    url += `&sort=${sortBy || 'OverallAverage'}`;
                    url += `&sort_direction=${sortDirection || 'desc'}`;
                    
                    // Show all important columns
                    url += `&show_rank=true`;
                    url += `&show_bib=true`;
                    url += `&show_participant=true`;
                    url += `&show_category=true`;
                    url += `&show_club=true`;
                    url += `&show_gender=false`;
                    url += `&show_country=false`;
                    url += `&show_runs=true`;
                    url += `&show_heat_best=true`;
                    url += `&show_heat_average=false`;
                    url += `&show_overall_best=true`;
                    url += `&show_highest_average=true`;
                    
                    const response = await fetch(url);
                    const data = await response.json();
                    
                    if (data.success && data.table_body) {
                        allTablesHTML += `
                            <div class="heat-section mb-4">
                                <div class="heat-section-header bg-primary text-white p-3 rounded-top">
                                    <div class="d-flex justify-content-between align-items-center">
                                        <h5 class="mb-0">
                                            <i class="fas fa-fire me-2"></i>${heatName}
                                        </h5>
                                        <span class="badge bg-light text-dark">
                                            <i class="fas fa-users me-1"></i>${data.participant_count || 0} Athletes
                                        </span>
                                    </div>
                                </div>
                                <div class="table-responsive">
                                    <style>${data.table_badge_colors || ''}</style>
                                    <table class="table table-striped table-hover table-sm mb-0">
                                        ${data.table_head || ''}
                                        ${data.table_body || ''}
                                    </table>
                                </div>
                            </div>
                        `;
                    } else {
                        allTablesHTML += `
                            <div class="heat-section mb-4">
                                <div class="heat-section-header bg-secondary text-white p-3 rounded">
                                    <h5 class="mb-0">
                                        <i class="fas fa-fire me-2"></i>${heatName}
                                    </h5>
                                </div>
                                <div class="alert alert-info mb-0">
                                    <i class="fas fa-info-circle me-2"></i>No results available
                                </div>
                            </div>
                        `;
                    }
                }
                
                allTablesHTML += '</div>';
                document.getElementById('contentDisplay').innerHTML = allTablesHTML;
                
            } catch (error) {
                document.getElementById('contentDisplay').innerHTML = `
                    <div class="alert alert-danger">
                        <i class="fas fa-exclamation-triangle me-2"></i>
                        Error loading results: ${error.message}
                    </div>
                `;
            }
        }
        
        // Helper function to display multiple heats stacked vertically
        async function displayHeatTablesStacked(eventId, heatNumbers, categoryFilter, sortBy, sortDirection,
            showRank, showBip, showParticipant, showCategory, showClub, showGender,
            showFisCode, showLicenceCode, showCountry, showRuns, showJudges,
            showControlPoints, showFigures, showEventSettings, showFormatName,
            showJudgeInfo, showScaleInfo, showDropRule, showModeConfig, showHeatInfo,
            showHeatBest, showHeatAverage, showOverallBest, showHighestAverage, genderFilter) {
            
            let allTablesHTML = '<div class="heat-tables-stacked">';
            
            // Fetch and display each heat separately
            for (const heatNum of heatNumbers) {
                try {
                    // Build URL for this specific heat
                    let url = `../api/summary_table_api.php?event_id=${eventId}`;
                    url += `&heat_number=${heatNum}`; // Explicit heat number filter
                    url += `&category=${encodeURIComponent(categoryFilter)}`;
                    url += `&heat_run_filter={"${heatNum}":[1,2,3]}`; // Heat/run filter for columns
                    url += `&show_rank=${showRank}`;
                    url += `&show_bib=${showBip}`;
                    url += `&show_participant=${showParticipant}`;
                    url += `&show_category=${showCategory}`;
                    url += `&show_club=${showClub}`;
                    url += `&show_gender=${showGender}`;
                    url += `&show_fis_code=${showFisCode}`;
                    url += `&show_licence_code=${showLicenceCode}`;
                    url += `&show_country=${showCountry}`;
                    url += `&show_runs=${showRuns}`;
                    url += `&show_judges=${showJudges}`;
                    url += `&show_control_points=${showControlPoints}`;
                    url += `&show_figures=${showFigures}`;
                    url += `&show_event_settings=${showEventSettings}`;
                    if (showEventSettings) {
                        url += `&show_format_name=${showFormatName}`;
                        url += `&show_judge_info=${showJudgeInfo}`;
                        url += `&show_scale_info=${showScaleInfo}`;
                        url += `&show_drop_rule=${showDropRule}`;
                        url += `&show_mode_config=${showModeConfig}`;
                        url += `&show_heat_info=${showHeatInfo}`;
                    }
                    url += `&show_heat_best=${showHeatBest}`;
                    url += `&show_heat_average=${showHeatAverage}`;
                    url += `&show_overall_best=${showOverallBest}`;
                    url += `&show_highest_average=${showHighestAverage}`;
                    url += `&sort=${sortBy}`;
                    url += `&sort_direction=${sortDirection}`;
                    url += `&gender=${genderFilter}`;
                    
                    const response = await fetch(url);
                    const data = await response.json();
                    
                    if (data.success) {
                        // Get heat name from heat_settings or use default
                        const heatName = data.heat_settings && data.heat_settings[heatNum] 
                            ? data.heat_settings[heatNum].name 
                            : 'Heat ' + heatNum;
                        
                        allTablesHTML += `
                            <div class="heat-table-wrapper mb-4">
                                <div class="heat-table-header bg-primary text-white p-2 rounded-top">
                                    <h5 class="mb-0"><i class="fas fa-fire me-2"></i>${heatName}</h5>
                                </div>
                                <div class="table-responsive">
                                    <style>${data.table_badge_colors || ''}</style>
                                    <table class="table table-striped table-hover mb-0">
                                        ${data.table_head || ''}
                                        ${data.table_body || ''}
                                    </table>
                                </div>
                                <div class="heat-table-footer bg-light p-2 rounded-bottom">
                                    <small class="text-muted">
                                        <i class="fas fa-users me-1"></i>${data.participant_count || 0} Participants
                                    </small>
                                </div>
                            </div>
                        `;
                    } else {
                        allTablesHTML += `
                            <div class="alert alert-warning mb-3">
                                <i class="fas fa-exclamation-triangle me-2"></i>
                                Heat ${heatNum}: ${data.message || 'No data available'}
                            </div>
                        `;
                    }
                } catch (error) {
                    allTablesHTML += `
                        <div class="alert alert-danger mb-3">
                            <i class="fas fa-exclamation-triangle me-2"></i>
                            Heat ${heatNum}: Error loading data - ${error.message}
                        </div>
                    `;
                }
            }
            
            allTablesHTML += '</div>';
            document.getElementById('contentDisplay').innerHTML = allTablesHTML;
        }
        
 function downloadSummaryCSV(configId) {
    window.open(`/v2/api/summary_table_api.php?config_id=${configId}&format=csv`, '_blank');
}

function viewSummaryJSON(configId) {
    window.open(`/v2/api/summary_table_api.php?config_id=${configId}&format=json`, '_blank');
}

function viewSummaryHTML(configId) {
    window.open(`/v2/api/summary_table_api.php?config_id=${configId}&format=html`, '_blank');
}
        
        function viewSummaryJSON() {
            const eventId = <?= json_encode($selected_event) ?>;
            const heatNumber = document.getElementById('heat_number')?.value || null;
            const categoryFilter = document.getElementById('category_filter')?.value ?? 'all';
            
            let url = `../api/summary_table_api.php?event_id=${eventId}&category=${categoryFilter}&format=json`;
            if (heatNumber && heatNumber !== '') {
                url += `&heat_run_filter={"${heatNumber}":[1,2,3]}`;
            }
            window.open(url, '_blank');
        }
        
        function refreshContent() {
            document.getElementById('contentDisplay').innerHTML = `
                <div class="text-center py-4">
                    <div class="spinner-border text-primary" role="status">
                        <span class="visually-hidden">Refreshing...</span>
                    </div>
                    <p class="mt-2 text-muted">Refreshing content...</p>
                </div>
            `;
            loadContent();
        }

        function toggleEventSettingsDetails() {
            const showEventSettingsElement = document.getElementById('showEventSettings');
            const detailsElement = document.getElementById('eventSettingsDetails');
            
            if (!showEventSettingsElement || !detailsElement) {
                console.warn('Event settings elements not found:', {
                    showEventSettings: !!showEventSettingsElement,
                    eventSettingsDetails: !!detailsElement
                });
                return;
            }
            
            const showEventSettings = showEventSettingsElement.checked;
            
            if (showEventSettings) {
                detailsElement.style.display = 'block';
            } else {
                detailsElement.style.display = 'none';
            }
        }
        
        // Live refresh functionality
        let liveRefreshInterval = null;
        
        function toggleLiveRefresh() {
            const showLiveCheckbox = document.getElementById('showLive');
            
            if (!showLiveCheckbox) {
                console.warn('showLive checkbox not found');
                return;
            }
            
            const isEnabled = showLiveCheckbox.checked;
            
            // Clear any existing interval
            if (liveRefreshInterval) {
                clearInterval(liveRefreshInterval);
                liveRefreshInterval = null;
                console.log('Live refresh stopped');
            }
            
            if (isEnabled) {
                // Start auto-refresh every 5 seconds
                console.log('Live refresh started (5 second interval)');
                liveRefreshInterval = setInterval(() => {
                    console.log('Auto-refreshing content...');
                    loadContent();
                }, 5000);
                
                // Also refresh immediately when enabled
                loadContent();
            }
        }
        
        // Configuration Management Functions
        function generateConfigName() {
            const eventId = <?= json_encode($selected_event) ?>;
            const eventName = document.querySelector('#event_id option:checked')?.text || 'Event';
            const heatSelect = document.getElementById('heat_number');
            const selectedHeats = heatSelect ? Array.from(heatSelect.selectedOptions)
                .map(option => option.value)
                .filter(value => value !== '') : [];
            const heatText = selectedHeats.length > 0 ? 
                (selectedHeats.length === 1 ? ` - Heat ${selectedHeats[0]}` : ` - Heats ${selectedHeats.join(',')}`) : '';
            const categoryFilter = document.getElementById('category_filter')?.value;
            const categoryText = (categoryFilter && categoryFilter !== 'all') ? ` - ${categoryFilter}` : '';
            const viewType = currentViewType === 'summary_table' ? 'Summary Table' : 'Start List';
            
            const suggestedName = `${viewType} - ${eventName}${heatText}${categoryText}`;
            
            // Add null checks to prevent errors
            const configNameEl = document.getElementById('configName');
            const suggestedNameEl = document.getElementById('suggestedName');
            
            if (configNameEl) {
                configNameEl.value = suggestedName;
            }
            if (suggestedNameEl) {
                suggestedNameEl.textContent = `Suggested: ${suggestedName}`;
            }
        }
        
        function getCurrentConfiguration() {
            // Capture main filter values from the Filters section
            // Get heat_number as array for multi-select support
            const heatSelect = document.getElementById('heat_number');
            let heatNumbers = null;
            if (heatSelect) {
                const selectedHeats = Array.from(heatSelect.selectedOptions)
                    .map(option => option.value)
                    .filter(value => value !== '');
                if (selectedHeats.length > 0) {
                    heatNumbers = selectedHeats.length === 1 ? selectedHeats[0] : selectedHeats;
                }
            }
            
            const mainFilters = {
                event_id: document.getElementById('event_id')?.value ?? '',
                heat_number: heatNumbers,
                gender_filter_main: document.getElementById('gender_filter_main')?.value ?? 'all',
                category_filter: document.getElementById('category_filter')?.value ?? 'all'
            };
            
            if (currentViewType === 'summary_table') {
                return {
                    // Main filters from Filters section
                    ...mainFilters,
                    
                    // Basic columns
                    showRank: document.getElementById('showRank')?.checked ?? true,
                    showBib: document.getElementById('showBip')?.checked ?? true,
                    showParticipant: document.getElementById('showParticipant')?.checked ?? true,
                    showCategory: document.getElementById('showCategory')?.checked ?? true,
                    showClub: document.getElementById('showClub')?.checked ?? true,
                    showGender: document.getElementById('showGender')?.checked ?? true,
                    showFisCode: document.getElementById('showFisCode')?.checked ?? false,
                    showLicenceCode: document.getElementById('showLicenceCode')?.checked ?? false,
                    showCountry: document.getElementById('showCountry')?.checked ?? false,
                    showBirthYear: document.getElementById('showBirthYear')?.checked ?? false,
                    showAge: document.getElementById('showAge')?.checked ?? false,
                    
                    // Aggregation columns
                    showRuns: document.getElementById('showRuns')?.checked ?? true,
                    showJudges: document.getElementById('showJudges')?.checked ?? false,
                    showControlPoints: document.getElementById('showControlPoints')?.checked ?? false,
                    showFigures: document.getElementById('showFigures')?.checked ?? false,
                    showEventSettings: document.getElementById('showEventSettings')?.checked ?? false,
                    showHeatBest: document.getElementById('showHeatBest')?.checked ?? true,
                    showHeatAverage: document.getElementById('showHeatAverage')?.checked ?? false,
                    showOverallBest: document.getElementById('showOverallBest')?.checked ?? false,
                    showHighestAverage: document.getElementById('showHighestAverage')?.checked ?? false,
                    
                    // Heat display options
                    heatDirection: document.querySelector('input[name="heatDirection"]:checked')?.value ?? 'row',
                    
                    // Event settings detail toggles
                    showFormatName: document.getElementById('showFormatName')?.checked ?? true,
                    showJudgeInfo: document.getElementById('showJudgeInfo')?.checked ?? true,
                    showScaleInfo: document.getElementById('showScaleInfo')?.checked ?? true,
                    showDropRule: document.getElementById('showDropRule')?.checked ?? true,
                    showModeConfig: document.getElementById('showModeConfig')?.checked ?? false,
                    showHeatInfo: document.getElementById('showHeatInfo')?.checked ?? true,
                    
                    // Filters and sorting
                    sortBy: document.getElementById('sortBy')?.value ?? 'OverallAverage',
                    sortDirection: document.getElementById('sortDirection')?.value ?? 'desc',
                    gender: document.getElementById('genderFilter')?.value ?? 'all',
                    
                    // Live refresh option
                    showLive: document.getElementById('showLive')?.checked ?? false,
                    
                    // Column renames
                    columnRenames: currentColumnRenames || {}
                };
            } else {
                return {
                    // Main filters from Filters section
                    ...mainFilters,
                    
                    // Basic columns for start list
                    showRank: document.getElementById('showRank')?.checked ?? true,
                    showBib: document.getElementById('showBip')?.checked ?? true,
                    showParticipant: document.getElementById('showParticipant')?.checked ?? true,
                    showCategory: document.getElementById('showCategory')?.checked ?? true,
                    showClub: document.getElementById('showClub')?.checked ?? true,
                    showGender: document.getElementById('showGender')?.checked ?? true,
                    showFisCode: document.getElementById('showFisCode')?.checked ?? false,
                    showLicenceCode: document.getElementById('showLicenceCode')?.checked ?? false,
                    showCountry: document.getElementById('showCountry')?.checked ?? false,
                    showBirthYear: document.getElementById('showBirthYear')?.checked ?? false,
                    showAge: document.getElementById('showAge')?.checked ?? false,
                    
                    // Score columns for start list
                    showRuns: document.getElementById('showRuns')?.checked ?? true,
                    showJudges: document.getElementById('showJudges')?.checked ?? false,
                    showControlPoints: document.getElementById('showControlPoints')?.checked ?? false,
                    showFigures: document.getElementById('showFigures')?.checked ?? false,
                    
                    // Sorting options for start list
                    sortBy: document.getElementById('sortBy')?.value ?? 'sort_order',
                    sortDirection: document.getElementById('sortDirection')?.value ?? 'asc',
                    genderFilter: document.getElementById('genderFilter')?.value ?? 'all',
                    
                    // Live refresh option
                    showLive: document.getElementById('showLive')?.checked ?? false,
                    
                    // Column renames
                    columnRenames: currentColumnRenames || {}
                };
            }
        }
        
        // DEPRECATED: Old saveCurrentConfiguration function - replaced with editing mode
        /*
        function saveCurrentConfiguration() {
            const configName = document.getElementById('configName').value.trim();
            const configStatus = document.getElementById('configStatus').value;
            const configOrder = parseInt(document.getElementById('configOrder').value) || 0;
            
            if (!configName) {
                alert('Please enter a configuration name');
                return;
            }
            
            const flatConfiguration = getCurrentConfiguration();
            
            const data = {
                action: 'save',
                name: configName,
                view_type: currentViewType,
                event_id: <?= json_encode($selected_event) ?>,
                heat_number: <?= json_encode($selected_heat) ?>,
                category: document.getElementById('category_filter')?.value || 'all',
                configuration: flatConfiguration,
                display_order: configOrder,
                status: configStatus
            };
            
            fetch('../api/result_configurations_api.php', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify(data)
            })
            .then(response => response.json())
            .then(result => {
                if (result.success) {
                    alert('Configuration saved successfully!');
                    // Clear the form
                    document.getElementById('configName').value = '';
                    document.getElementById('configOrder').value = '0';
                    document.getElementById('configStatus').value = 'draft';
                    // Refresh the page to show the new configuration
                    window.location.reload();
                } else {
                    alert('Error saving configuration: ' + result.message);
                }
            })
            .catch(error => {
                alert('Error saving configuration: ' + error.message);
            });
        }
        */
        
        function loadConfiguration(configId) {
            console.log('Loading configuration with ID:', configId);
            
            // Set a flag to prevent loadContent from being called multiple times
            window.isLoadingConfiguration = true;
            
            fetch(`../api/result_configurations_api.php?action=get&id=${configId}`)
            .then(response => {
                console.log('Response status:', response.status);
                return response.json();
            })
            .then(result => {
                console.log('API response:', result);
                if (result.success) {
                    const config = result.data;
                    console.log('Loading configuration:', config);

                    // Check if we're in editing mode and cancel the edit before loading new configuration
                    const mainCard = document.querySelector('.card.mb-3:has(.main-content)') || document.querySelector('.main-content')?.closest('.card');
                    if (mainCard && mainCard.classList.contains('editing-mode')) {
                        console.log('Cancelling configuration edit before loading new configuration...');
                        cancelConfigurationEdit();
                    }

                    // Switch to the correct view type if needed
                    if (config.view_type !== currentViewType) {
                        console.log('Switching view type from', currentViewType, 'to', config.view_type);
                        window.isLoadingConfiguration = false;
                        switchView(config.view_type);
                        return;
                    }

                    // First, update main filters directly from configuration data
                    console.log('Updating main filters from configuration...');
                    
                    // Update heat_number from top-level config (WITHOUT triggering change event)
                    if (document.getElementById('heat_number')) {
                        const heatSelect = document.getElementById('heat_number');
                        // Clear current selection first
                        Array.from(heatSelect.options).forEach(opt => opt.selected = false);
                        
                        // If config has heat_number (not null/empty), select those heats
                        if (config.heat_number) {
                            // Handle both single value and JSON array
                            let heatNumbers = [];
                            if (typeof config.heat_number === 'string' && config.heat_number.startsWith('[')) {
                                // It's a JSON array string
                                try {
                                    heatNumbers = JSON.parse(config.heat_number);
                                } catch (e) {
                                    heatNumbers = [config.heat_number];
                                }
                            } else if (Array.isArray(config.heat_number)) {
                                heatNumbers = config.heat_number;
                            } else {
                                heatNumbers = [config.heat_number];
                            }
                            
                            // Select all matching options
                            heatNumbers.forEach(heatNum => {
                                const option = Array.from(heatSelect.options).find(opt => opt.value == heatNum);
                                if (option) {
                                    option.selected = true;
                                }
                            });
                            
                            console.log('Updated heat_number to:', heatNumbers);
                        } else {
                            // No heat_number specified - select "All Heats" option (empty value)
                            const allHeatsOption = Array.from(heatSelect.options).find(opt => opt.value === '');
                            if (allHeatsOption) {
                                allHeatsOption.selected = true;
                            }
                            console.log('Updated heat_number to: All Heats (no filter)');
                        }
                    }
                    
                    // Update category from top-level config (WITHOUT triggering change event)
                    if (config.category && document.getElementById('category_filter')) {
                        const categorySelect = document.getElementById('category_filter');
                        categorySelect.value = config.category;
                        // Don't dispatch change event
                        console.log('Updated category_filter to:', config.category);
                    }
                    
                    // Update filters from configuration object (WITHOUT triggering change events)
                    if (config.configuration) {
                        if (config.configuration.gender_filter_main && document.getElementById('gender_filter_main')) {
                            const genderSelect = document.getElementById('gender_filter_main');
                            genderSelect.value = config.configuration.gender_filter_main;
                            // Don't dispatch change event
                            console.log('Updated gender_filter_main to:', config.configuration.gender_filter_main);
                        }
                        
                        if (config.configuration.category_filter && document.getElementById('category_filter')) {
                            const categorySelect = document.getElementById('category_filter');
                            categorySelect.value = config.configuration.category_filter;
                            // Don't dispatch change event
                            console.log('Updated category_filter to:', config.configuration.category_filter);
                        }
                    }

                    // Apply column filters and other settings based on view type
                    if (currentViewType === 'summary_table' && config.configuration) {
                        applyConfigurationToSummaryTable(config.configuration);
                    } else if (currentViewType === 'start_list' && config.configuration) {
                        applyConfigurationToStartList(config.configuration);
                    }

                    // Load the content ONCE with the new configuration applied
                    console.log('Loading content with new configuration...');
                    window.isLoadingConfiguration = false;
                    loadContent();
                    console.log('Configuration loaded successfully');

                } else {
                    console.error('Configuration load failed:', result);
                    alert('Error loading configuration: ' + result.message);
                }
            })
            .catch(error => {
                console.error('Configuration load error:', error);
                alert('Error loading configuration: ' + error.message);
            });
        }
        
        function applyConfigurationToSummaryTable(filters) {
            try {
                console.log('Applying configuration to summary table:', filters);
                
                // Apply main filter values from Filters section
                if (filters.event_id && document.getElementById('event_id')) {
                    document.getElementById('event_id').value = filters.event_id;
                }
                if (document.getElementById('heat_number')) {
                    const heatSelect = document.getElementById('heat_number');
                    // Clear current selection first
                    Array.from(heatSelect.options).forEach(opt => opt.selected = false);
                    
                    // If filters has heat_number (not null/empty), select those heats
                    if (filters.heat_number) {
                        // Handle both single value and JSON array
                        let heatNumbers = [];
                        if (typeof filters.heat_number === 'string' && filters.heat_number.startsWith('[')) {
                            // It's a JSON array string
                            try {
                                heatNumbers = JSON.parse(filters.heat_number);
                            } catch (e) {
                                heatNumbers = [filters.heat_number];
                            }
                        } else if (Array.isArray(filters.heat_number)) {
                            heatNumbers = filters.heat_number;
                        } else {
                            heatNumbers = [filters.heat_number];
                        }
                        
                        // Select all matching options
                        heatNumbers.forEach(heatNum => {
                            const option = Array.from(heatSelect.options).find(opt => opt.value == heatNum);
                            if (option) {
                                option.selected = true;
                            }
                        });
                        
                        // Don't dispatch change event - handled in loadConfiguration
                        console.log('Updated heat_number in summary table to:', heatNumbers);
                    } else {
                        // No heat_number specified - select "All Heats" option (empty value)
                        const allHeatsOption = Array.from(heatSelect.options).find(opt => opt.value === '');
                        if (allHeatsOption) {
                            allHeatsOption.selected = true;
                        }
                        console.log('Updated heat_number in summary table to: All Heats (no filter)');
                    }
                }
                if (filters.gender_filter_main && document.getElementById('gender_filter_main')) {
                    const genderSelect = document.getElementById('gender_filter_main');
                    genderSelect.value = filters.gender_filter_main;
                    // Don't dispatch change event - handled in loadConfiguration
                    console.log('Updated gender_filter_main to:', filters.gender_filter_main);
                }
                if (filters.category_filter && document.getElementById('category_filter')) {
                    const categorySelect = document.getElementById('category_filter');
                    categorySelect.value = filters.category_filter;
                    // Don't dispatch change event - handled in loadConfiguration
                    console.log('Updated category_filter to:', filters.category_filter);
                }
                
                // Column toggles - handle both boolean values and string values
                const columnMappings = {
                    'showRank': ['showRank', 'show_rank'],
                    'showBip': ['showBIB', 'show_bib'], // Note: config might use different key names
                    'showParticipant': ['showParticipant', 'show_participant'],
                    'showCategory': ['showCategory', 'show_category'],
                    'showClub': ['showClub', 'show_club'],
                    'showGender': ['showGender', 'show_gender'],
                    'showFisCode': ['showFisCode', 'show_fis_code'],
                    'showLicenceCode': ['showLicenceCode', 'show_licence_code'],
                    'showCountry': ['showCountry', 'show_country'],
                    'showBirthYear': ['showBirthYear', 'show_birth_year'],
                    'showAge': ['showAge', 'show_age'],
                    'showRuns': ['showRuns', 'show_runs'],
                    'showJudges': ['showJudges', 'show_judges'],
                    'showControlPoints': ['showControlPoints', 'show_control_points'],
                    'showFigures': ['showFigures', 'show_figures'],
                    'showEventSettings': ['showEventSettings', 'show_event_settings'],
                    'showHeatBest': ['showHeatBest', 'show_heat_best'],
                    'showHeatAverage': ['showHeatAverage', 'show_heat_average'],
                    'showOverallBest': ['showOverallBest', 'show_overall_best'],
                    'showHighestAverage': ['showHighestAverage', 'show_highest_average']
                };

                // Apply column toggles
                for (const [elementId, configKeys] of Object.entries(columnMappings)) {
                    const element = document.getElementById(elementId);
                    if (element) {
                        let value = null;
                        // Try each possible config key
                        for (const key of configKeys) {
                            if (filters.hasOwnProperty(key)) {
                                value = filters[key];
                                break;
                            }
                        }
                        
                        if (value !== null) {
                            // Handle both string and boolean values
                            element.checked = (value === true || value === 'true' || value === '1' || value === 1);
                            console.log(`Set ${elementId} to ${element.checked} (from ${value})`);
                        }
                    }
                }

                // Apply event settings detail toggles
                const eventSettingsToggles = {
                    'showFormatName': 'showFormatName',
                    'showJudgeInfo': 'showJudgeInfo', 
                    'showScaleInfo': 'showScaleInfo',
                    'showDropRule': 'showDropRule',
                    'showModeConfig': 'showModeConfig',
                    'showHeatInfo': 'showHeatInfo'
                };
                
                for (const [elementId, configKey] of Object.entries(eventSettingsToggles)) {
                    const element = document.getElementById(elementId);
                    if (element && filters.hasOwnProperty(configKey)) {
                        const value = filters[configKey];
                        element.checked = (value === true || value === 'true' || value === '1' || value === 1);
                        console.log(`Set event setting ${elementId} to ${element.checked} (from ${value})`);
                    }
                }

                // Apply sort settings
                if (filters.sortBy && document.getElementById('sortBy')) {
                    document.getElementById('sortBy').value = filters.sortBy;
                }
                if (filters.sortDirection && document.getElementById('sortDirection')) {
                    document.getElementById('sortDirection').value = filters.sortDirection;
                }
                
                // Apply heat direction (radio buttons)
                if (filters.heatDirection) {
                    const heatDirValue = filters.heatDirection;
                    if (heatDirValue === 'row') {
                        const rowRadio = document.getElementById('heatDirectionRow');
                        if (rowRadio) {
                            rowRadio.checked = true;
                            console.log('Set heat direction to: row');
                        }
                    } else if (heatDirValue === 'column') {
                        const colRadio = document.getElementById('heatDirectionColumn');
                        if (colRadio) {
                            colRadio.checked = true;
                            console.log('Set heat direction to: column');
                        }
                    }
                }

                // Apply gender filter (if different from main filter)
                if (filters.genderFilter && document.getElementById('genderFilter')) {
                    document.getElementById('genderFilter').value = filters.genderFilter;
                }

                // Apply heat settings
                if (filters.heat_settings) {
                    let heatSettings = filters.heat_settings;
                    if (typeof heatSettings === 'string') {
                        try {
                            heatSettings = JSON.parse(heatSettings);
                        } catch (e) {
                            console.error('Error parsing heat_settings:', e);
                        }
                    }
                    
                    if (typeof heatSettings === 'object') {
                        for (const [heatNum, enabled] of Object.entries(heatSettings)) {
                            const checkbox = document.querySelector(`input[name="heat_settings[${heatNum}]"]`);
                            if (checkbox) {
                                checkbox.checked = enabled === true || enabled === 'true' || enabled === '1' || enabled === 1;
                            }
                        }
                    }
                }

                // Apply column renames
                if (filters.columnRenames) {
                    currentColumnRenames = filters.columnRenames;
                    localStorage.setItem('columnRenames_' + <?= json_encode($selected_event) ?>, JSON.stringify(currentColumnRenames));
                    console.log('Applied column renames:', currentColumnRenames);
                    // Apply renames to the UI inputs in the Toggle Panel
                    applyRenamesToModal();
                }
                
                // Apply live refresh setting
                if (document.getElementById('showLive')) {
                    const showLiveValue = filters.showLive || filters.show_live;
                    document.getElementById('showLive').checked = (showLiveValue === true || showLiveValue === 'true' || showLiveValue === '1' || showLiveValue === 1);
                    console.log('Set showLive to:', document.getElementById('showLive').checked);
                    // Start/stop live refresh based on the setting
                    toggleLiveRefresh();
                }

                console.log('Configuration applied successfully');
            } catch (error) {
                console.error('Error applying configuration:', error);
            }
        }
        
        function applyConfigurationToStartList(filters) {
            // Apply main filter values from Filters section
            if (filters.event_id && document.getElementById('event_id')) {
                document.getElementById('event_id').value = filters.event_id;
            }
            if (document.getElementById('heat_number')) {
                const heatSelect = document.getElementById('heat_number');
                // Clear current selection first
                Array.from(heatSelect.options).forEach(opt => opt.selected = false);
                
                // If filters has heat_number (not null/empty), select those heats
                if (filters.heat_number) {
                    // Handle both single value and JSON array
                    let heatNumbers = [];
                    if (typeof filters.heat_number === 'string' && filters.heat_number.startsWith('[')) {
                        // It's a JSON array string
                        try {
                            heatNumbers = JSON.parse(filters.heat_number);
                        } catch (e) {
                            heatNumbers = [filters.heat_number];
                        }
                    } else if (Array.isArray(filters.heat_number)) {
                        heatNumbers = filters.heat_number;
                    } else {
                        heatNumbers = [filters.heat_number];
                    }
                    
                    // Select all matching options
                    heatNumbers.forEach(heatNum => {
                        const option = Array.from(heatSelect.options).find(opt => opt.value == heatNum);
                        if (option) {
                            option.selected = true;
                        }
                    });
                    
                    console.log('Updated heat_number in start list to:', heatNumbers);
                } else {
                    // No heat_number specified - select "All Heats" option (empty value)
                    const allHeatsOption = Array.from(heatSelect.options).find(opt => opt.value === '');
                    if (allHeatsOption) {
                        allHeatsOption.selected = true;
                    }
                    console.log('Updated heat_number in start list to: All Heats (no filter)');
                }
            }
            if (filters.gender_filter_main && document.getElementById('gender_filter_main')) {
                const genderSelect = document.getElementById('gender_filter_main');
                genderSelect.value = filters.gender_filter_main;
                genderSelect.dispatchEvent(new Event('change'));
                console.log('Updated gender_filter_main to:', filters.gender_filter_main);
            }
            if (filters.category_filter && document.getElementById('category_filter')) {
                const categorySelect = document.getElementById('category_filter');
                categorySelect.value = filters.category_filter;
                categorySelect.dispatchEvent(new Event('change'));
                console.log('Updated category_filter to:', filters.category_filter);
            }
            
            // Apply basic column visibility for start list
            const basicColumns = ['showRank', 'showBip', 'showParticipant', 'showCategory', 'showClub', 'showGender', 'showFisCode', 'showLicenceCode', 'showCountry', 'showBirthYear', 'showAge'];
            basicColumns.forEach(col => {
                const element = document.getElementById(col);
                if (element && filters.hasOwnProperty(col)) {
                    const value = filters[col];
                    if (typeof value === 'boolean') {
                        element.checked = value;
                    } else if (typeof value === 'string') {
                        element.checked = value === 'true' || value === '1';
                    }
                    console.log(`Updated ${col} to:`, element.checked);
                }
            });
            
            // Apply score column visibility for start list
            const scoreColumns = ['showRuns', 'showJudges', 'showControlPoints', 'showFigures'];
            scoreColumns.forEach(col => {
                const element = document.getElementById(col);
                if (element && filters.hasOwnProperty(col)) {
                    const value = filters[col];
                    if (typeof value === 'boolean') {
                        element.checked = value;
                    } else if (typeof value === 'string') {
                        element.checked = value === 'true' || value === '1';
                    }
                    console.log(`Updated ${col} to:`, element.checked);
                }
            });

            // Apply sorting options for start list
            if (filters.sortBy) {
                const sortSelect = document.getElementById('sortBy');
                if (sortSelect) {
                    sortSelect.value = filters.sortBy;
                    console.log('Updated sortBy to:', filters.sortBy);
                }
            }

            if (filters.sortDirection) {
                const sortDirSelect = document.getElementById('sortDirection');
                if (sortDirSelect) {
                    sortDirSelect.value = filters.sortDirection;
                    console.log('Updated sortDirection to:', filters.sortDirection);
                }
            }

            // Apply gender filter
            if (filters.genderFilter) {
                const genderSelect = document.getElementById('genderFilter');
                if (genderSelect) {
                    genderSelect.value = filters.genderFilter;
                    console.log('Updated genderFilter to:', filters.genderFilter);
                }
            }
            
            // Apply column renames
            if (filters.columnRenames) {
                currentColumnRenames = filters.columnRenames;
                console.log('Applied column renames:', filters.columnRenames);
            }
            
            // Apply live refresh setting
            if (document.getElementById('showLive')) {
                const showLiveValue = filters.showLive || filters.show_live;
                document.getElementById('showLive').checked = (showLiveValue === true || showLiveValue === 'true' || showLiveValue === '1' || showLiveValue === 1);
                console.log('Set showLive to:', document.getElementById('showLive').checked);
                // Start/stop live refresh based on the setting
                toggleLiveRefresh();
            }
            
            // Apply start list filter settings (for backward compatibility)
            if (document.getElementById('gender_filter_main') && filters.genderFilter && !filters.gender_filter_main) {
                const genderSelect = document.getElementById('gender_filter_main');
                genderSelect.value = filters.genderFilter ?? 'all';
                genderSelect.dispatchEvent(new Event('change'));
                console.log('Updated gender_filter_main (legacy) to:', filters.genderFilter);
            }
        }
        
        function deleteConfiguration(configId, configName) {
            if (!confirm(`Are you sure you want to delete the configuration "${configName}"?`)) {
                return;
            }
            
            fetch('../api/result_configurations_api.php?action=delete', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({ id: configId })
            })
            .then(response => response.json())
            .then(result => {
                if (result.success) {
                    alert('Configuration deleted successfully!');
                    window.location.reload();
                } else {
                    alert('Error deleting configuration: ' + result.message);
                }
            })
            .catch(error => {
                alert('Error deleting configuration: ' + error.message);
            });
        }
        
        // Auto-generate name when filters change
        document.addEventListener('DOMContentLoaded', function() {
            // Generate suggested name on page load
            setTimeout(generateConfigName, 500);
            
            // Update suggested name when filters change
            ['event_id', 'heat_number', 'category_filter', 'gender_filter_main'].forEach(id => {
                const element = document.getElementById(id);
                if (element) {
                    element.addEventListener('change', generateConfigName);
                }
            });
        });
        
        let editConfigId = null;
        let editConfigModalInstance = null;
        let editConfigData = null; // NEW: keep full config for event_id/view_type

        function showEditError(msg) {
            const el = document.getElementById('editConfigAlert');
            if (el) {
                el.textContent = msg || 'Unknown error';
                el.classList.remove('d-none');
            }
        }
        function hideEditError() {
            const el = document.getElementById('editConfigAlert');
            if (el) {
                el.textContent = '';
                el.classList.add('d-none');
            }
        }

        function editConfiguration(configId) {
            console.log('Starting editConfiguration with ID:', configId);
            editConfigId = configId;

            try {
                fetch(`../api/result_configurations_api.php?action=get&id=${configId}`)
                .then(r => r.json())
                .then(res => {
                    console.log('Configuration API response:', res);
                    if (!res.success) throw new Error(res.message || 'Failed to load configuration');
                    const cfg = res.data || {};
                    console.log('Configuration data:', cfg);
                    editConfigData = cfg;

                    try {
                        // Enable editing mode
                        console.log('Entering editing mode...');
                        enterEditingMode(cfg.name || 'Unnamed Configuration');
                        console.log('Editing mode entered successfully');

                        // Parse the configuration filters
                        let filters = cfg.configuration || {};
                        if (typeof filters === 'string') {
                            try { 
                                filters = JSON.parse(filters); 
                                console.log('Parsed filters:', filters);
                            } catch(e) {
                                console.error('Error parsing configuration filters:', e);
                                filters = {};
                            }
                        }

                        // Apply configuration to main UI
                        console.log('Applying configuration to UI...');
                        applyConfigurationToUI(filters);
                        console.log('Configuration applied successfully');
                        
                        // Update the summary table with loaded configuration
                        console.log('Loading summary table...');
                        loadSummaryTable();
                        console.log('Summary table loaded successfully');
                        
                    } catch(uiError) {
                        console.error('Error in UI updates:', uiError);
                        alert('Error updating UI: ' + uiError.message);
                    }
                })
                .catch(err => {
                    console.error('Error loading configuration:', err);
                    alert('Error loading configuration: ' + err.message);
                });
            } catch(generalError) {
                console.error('General error in editConfiguration:', generalError);
                alert('General error: ' + generalError.message);
            }
        }

        function enterEditingMode(configName) {
            // Show editing banner and config details
            document.getElementById('editingModeBanner').classList.remove('d-none');
            document.getElementById('editConfigDetails').classList.remove('d-none');
            document.getElementById('editingConfigName').textContent = configName;
            
            // Add editing mode class to main content card
            const mainCard = document.getElementById('mainContentCard');
            if (mainCard) {
                mainCard.classList.add('editing-mode');
            }
        }

        function cancelConfigurationEdit() {
            exitEditingMode();
            // Reload the page to reset all settings
            window.location.reload();
        }

        function exitEditingMode() {
            // Hide editing banner and config details
            document.getElementById('editingModeBanner').classList.add('d-none');
            document.getElementById('editConfigDetails').classList.add('d-none');
            document.getElementById('editingConfigName').textContent = '';
            
            // Remove editing mode class
            const mainCard = document.getElementById('mainContentCard');
            if (mainCard) {
                mainCard.classList.remove('editing-mode');
            }
            
            editConfigId = null;
            editConfigData = null;
        }

        function applyConfigurationToUI(filters) {
            // Apply basic column visibility
            const basicColumns = ['showRank', 'showBip', 'showParticipant', 'showCategory', 'showClub', 'showGender', 'showFisCode', 'showLicenceCode', 'showCountry'];
            basicColumns.forEach(col => {
                const element = document.getElementById(col);
                if (element && filters.hasOwnProperty(col)) {
                    element.checked = filters[col] === true;
                }
            });

            // Apply aggregation column visibility
            const aggregationColumns = ['showRuns', 'showJudges', 'showControlPoints', 'showFigures', 'showEventSettings', 'showHeatBest', 'showHeatAverage', 'showOverallBest', 'showHighestAverage'];
            aggregationColumns.forEach(col => {
                const element = document.getElementById(col);
                if (element && filters.hasOwnProperty(col)) {
                    element.checked = filters[col] === true;
                }
            });

            // Apply event settings detail toggles
            const eventDetailColumns = ['showFormatName', 'showJudgeInfo', 'showScaleInfo', 'showDropRule', 'showModeConfig', 'showHeatInfo'];
            eventDetailColumns.forEach(col => {
                const element = document.getElementById(col);
                if (element && filters.hasOwnProperty(col)) {
                    element.checked = filters[col] === true;
                }
            });

            // Apply sorting
            if (filters.sortBy) {
                const sortSelect = document.getElementById('sortBy');
                if (sortSelect) {
                    sortSelect.value = filters.sortBy;
                }
            }

            if (filters.sortDirection) {
                const sortDirSelect = document.getElementById('sortDirection');
                if (sortDirSelect) {
                    sortDirSelect.value = filters.sortDirection;
                }
            }

            // Apply gender filter
            if (filters.gender) {
                const genderSelect = document.getElementById('genderFilter');
                if (genderSelect) {
                    genderSelect.value = filters.gender;
                }
            }

            // Update configuration form fields with loaded data
            if (editConfigData) {
                const configNameField = document.getElementById('editConfigName');
                const configStatusField = document.getElementById('editConfigStatus');
                const configOrderField = document.getElementById('editConfigOrder');
                const configViewTypeField = document.getElementById('editConfigViewType');
                
                if (configNameField) {
                    configNameField.value = editConfigData.name || '';
                }
                if (configStatusField) {
                    configStatusField.value = editConfigData.status || 'draft';
                }
                if (configOrderField) {
                    configOrderField.value = editConfigData.display_order || 0;
                }
                if (configViewTypeField) {
                    configViewTypeField.value = editConfigData.view_type || '';
                }
            }

            // Update event settings details visibility
            try {
                toggleEventSettingsDetails();
            } catch(toggleError) {
                console.error('Error toggling event settings details:', toggleError);
            }
        }

        function saveEditedConfiguration() {
            if (!editConfigId || !editConfigData) {
                alert('No configuration being edited');
                return;
            }

            // Get current configuration from UI
            const currentConfig = getCurrentConfiguration();
            
            // Get updated values from form fields (user might have changed them)
            const configName = document.getElementById('editConfigName')?.value || editConfigData.name;
            const configStatus = document.getElementById('editConfigStatus')?.value || editConfigData.status;
            const configOrder = document.getElementById('editConfigOrder')?.value || editConfigData.display_order;

            const requestData = {
                action: 'save',
                id: editConfigId,
                name: configName,
                view_type: editConfigData.view_type,
                event_id: editConfigData.event_id,
                heat_number: editConfigData.heat_number,
                category: editConfigData.category,
                status: configStatus,
                display_order: parseInt(configOrder) || 0,
                configuration: currentConfig
            };
            
            console.log('Saving configuration with data:', requestData);

            // Send update request
            fetch('../api/result_configurations_api.php', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify(requestData)
            })
            .then(r => r.json())
            .then(res => {
                console.log('Save response:', res);
                if (!res.success) throw new Error(res.message || 'Failed to update configuration');
                
                alert('Configuration updated successfully!');
                exitEditingMode();
                
                // Reload configurations list
                if (typeof loadConfigurations === 'function') {
                    loadConfigurations();
                }
            })
            .catch(err => {
                console.error('Save error:', err);
                alert('Error saving configuration: ' + err.message);
            });
        }

        function updateConfigurationSave() {
            hideEditError();
            if (!editConfigId) {
                showEditError('Missing configuration ID');
                return;
            }

            const name = document.getElementById('editConfigName').value.trim();
            const status = document.getElementById('editConfigStatus').value;
            const display_order = parseInt(document.getElementById('editConfigOrder').value) || 0;
            const heat_number_raw = document.getElementById('editConfigHeat').value;
            const category_raw = document.getElementById('editConfigCategory').value;
            const filtersText = document.getElementById('editConfigFilters').value;

            // NEW: ensure view_type and event_id are included
            const view_type = (document.getElementById('editConfigViewType')?.value || editConfigData?.view_type || currentViewType || '').trim();
            if (!view_type) {
                showEditError("View Type is required.");
                return;
            }
            const event_id = editConfigData?.event_id || document.getElementById('event_id')?.value || null;
            if (!event_id) {
                showEditError("Event ID is required.");
                return;
            }

            let configuration;
            try {
                configuration = filtersText ? JSON.parse(filtersText) : {};
            } catch (e) {
                showEditError('Filters JSON is invalid: ' + e.message);
                return;
            }

            const payload = {
                id: editConfigId,
                event_id,            // NEW
                view_type,           // NEW
                name,
                status,
                display_order,
                heat_number: heat_number_raw ? Number(heat_number_raw) : null,
                category: (category_raw && category_raw !== 'all') ? category_raw : null,
                configuration
            };

            const doRequest = (action) => fetch(`../api/result_configurations_api.php?action=${action}`, {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify(payload)
            }).then(r => r.json());

            doRequest('update')
            .then(res => {
                if (!res.success) {
                    if ((res.message || '').toLowerCase().includes('invalid action')) {
                        return doRequest('save');
                    }
                    throw new Error(res.message || 'Update failed');
                }
                return res;
            })
            .then(res => {
                if (!res.success) throw new Error(res.message || 'Save failed');
                editConfigModalInstance?.hide();
                window.location.reload();
            })
            .catch(err => {
                showEditError(err.message);
            });
        }

        // Enhanced Configuration Management UX Functions
        
        function filterConfigs() {
            const searchTerm = document.getElementById('configSearch').value.toLowerCase();
            const configCards = document.querySelectorAll('.config-card');
            
            configCards.forEach(card => {
                const configName = card.getAttribute('data-config-name') || '';
                const configType = card.getAttribute('data-config-type') || '';
                const configStatus = card.getAttribute('data-config-status') || '';
                
                const matches = configName.includes(searchTerm) || 
                              configType.includes(searchTerm) || 
                              configStatus.includes(searchTerm);
                              
                card.style.display = matches ? '' : 'none';
            });
        }
        
        function clearConfigSearch() {
            document.getElementById('configSearch').value = '';
            filterConfigs();
        }
        
        // Update bulk delete button visibility
        function updateBulkDeleteButton() {
            const checkboxes = document.querySelectorAll('.config-select-checkbox:checked');
            const bulkBtn = document.getElementById('bulkDeleteBtn');
            if (checkboxes.length > 0) {
                bulkBtn.style.display = 'inline-block';
                bulkBtn.innerHTML = `<i class="fas fa-trash"></i> Delete (${checkboxes.length})`;
            } else {
                bulkBtn.style.display = 'none';
            }
        }
        
        // Bulk delete selected configurations
        function bulkDeleteConfigs() {
            const checkboxes = document.querySelectorAll('.config-select-checkbox:checked');
            const ids = Array.from(checkboxes).map(cb => cb.value);
            
            if (ids.length === 0) return;
            
            if (!confirm(`Delete ${ids.length} configuration(s)?`)) return;
            
            // Delete each configuration
            let deletePromises = ids.map(id => {
                return fetch('../api/result_configurations_api.php', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({ action: 'delete', id: id })
                }).then(response => response.json());
            });
            
            Promise.all(deletePromises)
                .then(results => {
                    const allSuccess = results.every(r => r.success);
                    if (allSuccess) {
                        window.location.reload();
                    } else {
                        alert('Some configurations could not be deleted');
                        window.location.reload();
                    }
                })
                .catch(error => {
                    alert('Error: ' + error.message);
                });
        }
        
        function previewConfiguration(configId) {
            fetch(`../api/result_configurations_api.php?action=get&id=${configId}`)
            .then(response => response.json())
            .then(result => {
                if (result.success) {
                    const config = result.data;
                    showConfigPreviewModal(config);
                } else {
                    alert('Error loading configuration: ' + result.message);
                }
            })
            .catch(error => {
                alert('Error loading configuration: ' + error.message);
            });
        }
        
        function showConfigPreviewModal(config) {
            const modalHtml = `
                <div class="modal fade" id="previewModal" tabindex="-1">
                    <div class="modal-dialog modal-lg">
                        <div class="modal-content">
                            <div class="modal-header">
                                <h5 class="modal-title">
                                    <i class="fas fa-eye me-2"></i>Preview: ${config.name}
                                </h5>
                                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                            </div>
                            <div class="modal-body">
                                <div class="row g-3">
                                    <div class="col-md-6">
                                        <h6><i class="fas fa-info-circle me-2"></i>Basic Info</h6>
                                        <ul class="list-unstyled">
                                            <li><strong>Type:</strong> ${config.view_type.replace('_', ' ')}</li>
                                            <li><strong>Status:</strong> <span class="badge bg-${config.status === 'active' ? 'success' : 'secondary'}">${config.status}</span></li>
                                            <li><strong>Heat:</strong> ${config.heat_number || 'All heats'}</li>
                                            <li><strong>Category:</strong> ${config.category || 'All categories'}</li>
                                            <li><strong>Created:</strong> ${new Date(config.created_at).toLocaleDateString()}</li>
                                        </ul>
                                    </div>
                                    <div class="col-md-6">
                                        <h6><i class="fas fa-cogs me-2"></i>Settings</h6>
                                        <div class="small">
                                            <pre class="bg-light p-2 rounded" style="max-height: 200px; overflow-y: auto;">${JSON.stringify(config.configuration, null, 2)}</pre>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            <div class="modal-footer">
                                <button type="button" class="btn btn-primary" onclick="loadConfiguration(${config.id}); bootstrap.Modal.getInstance(document.getElementById('previewModal')).hide();">
                                    <i class="fas fa-download me-1"></i>Load This Configuration
                                </button>
                                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
                            </div>
                        </div>
                    </div>
                </div>
            `;
            
            // Remove existing preview modal if any
            const existingModal = document.getElementById('previewModal');
            if (existingModal) existingModal.remove();
            
            // Add new modal to body
            document.body.insertAdjacentHTML('beforeend', modalHtml);
            const modal = new bootstrap.Modal(document.getElementById('previewModal'));
            modal.show();
        }
        
        function duplicateConfiguration(configId) {
            fetch(`../api/result_configurations_api.php?action=get&id=${configId}`)
            .then(response => response.json())
            .then(result => {
                if (result.success) {
                    const config = result.data;
                    const newConfig = {
                        ...config,
                        name: config.name + ' (Copy)',
                        status: 'draft'
                    };
                    delete newConfig.id;
                    delete newConfig.created_at;
                    
                    return fetch('../api/result_configurations_api.php?action=save', {
                        method: 'POST',
                        headers: { 'Content-Type': 'application/json' },
                        body: JSON.stringify(newConfig)
                    });
                } else {
                    throw new Error(result.message);
                }
            })
            .then(response => response.json())
            .then(result => {
                if (result.success) {
                    showSuccessToast('Configuration duplicated successfully!');
                    setTimeout(() => window.location.reload(), 1000);
                } else {
                    throw new Error(result.message);
                }
            })
            .catch(error => {
                alert('Error duplicating configuration: ' + error.message);
            });
        }
        
        function toggleFavorite(configId) {
            // This would require adding a favorites field to the database
            // For now, show a placeholder
            showInfoToast('Favorites feature coming soon!');
        }
        
        function showSaveConfigModal() {
            // Only generate config name if the modal elements exist
            if (document.getElementById('configName')) {
                generateConfigName();
            }
            $('#saveConfigModal').modal('show');
            
            // Focus on the config name input
            setTimeout(() => {
                document.getElementById('configName')?.focus();
            }, 300);
        }
        
        function saveCurrentConfig() {
            // Generate suggested name and populate modal
            generateConfigNameForModal();
            
            // Set the view type
            const viewTypeInput = document.getElementById('saveConfigViewType');
            if (viewTypeInput) {
                viewTypeInput.value = currentViewType === 'summary_table' ? 'Summary Table' : 'Start List';
            }
            
            // Show the modal
            const modal = new bootstrap.Modal(document.getElementById('saveConfigModal'));
            modal.show();
            
            // Focus on the config name input after modal opens
            setTimeout(() => {
                document.getElementById('saveConfigName')?.focus();
            }, 300);
        }
        
        function generateConfigNameForModal() {
            const eventId = <?= json_encode($selected_event) ?>;
            const eventName = document.querySelector('#event_id option:checked')?.text || 'Event';
            const heatSelect = document.getElementById('heat_number');
            const selectedHeats = heatSelect ? Array.from(heatSelect.selectedOptions)
                .map(option => option.value)
                .filter(value => value !== '') : [];
            const heatText = selectedHeats.length > 0 ? 
                (selectedHeats.length === 1 ? ` - Heat ${selectedHeats[0]}` : ` - Heats ${selectedHeats.join(',')}`) : '';
            const categoryFilter = document.getElementById('category_filter')?.value;
            const categoryText = (categoryFilter && categoryFilter !== 'all') ? ` - ${categoryFilter}` : '';
            const viewType = currentViewType === 'summary_table' ? 'Summary Table' : 'Start List';
            
            const suggestedName = `${viewType} - ${eventName}${heatText}${categoryText}`;
            
            // Add null checks to prevent errors
            const configNameEl = document.getElementById('saveConfigName');
            const suggestedNameEl = document.getElementById('suggestedName');
            
            if (configNameEl) {
                configNameEl.value = suggestedName;
            }
            if (suggestedNameEl) {
                suggestedNameEl.textContent = `Suggested: ${suggestedName}`;
            }
        }
        
        function saveConfigurationFromModal() {
            const configName = document.getElementById('saveConfigName')?.value.trim();
            const configStatus = document.getElementById('saveConfigStatus')?.value || 'active';
            const configOrder = parseInt(document.getElementById('saveConfigOrder')?.value) || 0;
            
            if (!configName) {
                alert('Please enter a configuration name');
                return;
            }
            
            const flatConfiguration = getCurrentConfiguration();
            
            const data = {
                action: 'save',
                name: configName,
                view_type: currentViewType,
                event_id: <?= json_encode($selected_event) ?>,
                heat_number: flatConfiguration.heat_number,
                category: document.getElementById('category_filter')?.value || 'all',
                configuration: flatConfiguration,
                display_order: configOrder,
                status: configStatus
            };
            
            fetch('../api/result_configurations_api.php', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify(data)
            })
            .then(response => response.json())
            .then(result => {
                if (result.success) {
                    // Close the modal
                    const modal = bootstrap.Modal.getInstance(document.getElementById('saveConfigModal'));
                    modal.hide();
                    
                    showInfoToast('Configuration saved successfully!');
                    // Refresh the page to show the new configuration
                    setTimeout(() => {
                        window.location.reload();
                    }, 1000);
                } else {
                    alert('Error saving configuration: ' + result.message);
                }
            })
            .catch(error => {
                alert('Error saving configuration: ' + error.message);
            });
        }
        
        function showSuccessToast(message) {
            showToast(message, 'success');
        }
        
        function showInfoToast(message) {
            showToast(message, 'info');
        }
        
        function showToast(message, type = 'info') {
            const toastHtml = `
                <div class="toast align-items-center text-white bg-${type === 'success' ? 'success' : 'info'} border-0 position-fixed" 
                     style="top: 20px; right: 20px; z-index: 9999;" role="alert" aria-live="assertive" aria-atomic="true">
                    <div class="d-flex">
                        <div class="toast-body">
                            <i class="fas fa-${type === 'success' ? 'check' : 'info'}-circle me-2"></i>${message}
                        </div>
                        <button type="button" class="btn-close btn-close-white me-2 m-auto" data-bs-dismiss="toast"></button>
                    </div>
                </div>
            `;
            
            document.body.insertAdjacentHTML('beforeend', toastHtml);
            const toastElement = document.querySelector('.toast:last-child');
            const toast = new bootstrap.Toast(toastElement);
            toast.show();
            
            // Auto remove after hiding
            toastElement.addEventListener('hidden.bs.toast', () => {
                toastElement.remove();
            });
        }

        // Column Rename Management Functions
        
        let currentColumnRenames = {};
        
        function loadCurrentRenames() {
            // Load existing column renames from current configuration or localStorage
            const saved = localStorage.getItem('columnRenames_' + <?= json_encode($selected_event) ?>);
            if (saved) {
                currentColumnRenames = JSON.parse(saved);
                applyRenamesToModal();
            }
        }
        
        function applyRenamesToModal() {
            // Apply current renames to the modal inputs
            const renameMapping = {
                'rename_rank': 'rank',
                'rename_bib': 'bib',
                'rename_participant': 'participant',
                'rename_category': 'category',
                'rename_club': 'club',
                'rename_gender': 'gender',
                'rename_fis_code': 'fis_code',
                'rename_licence_code': 'licence_code',
                'rename_country': 'country',
                'rename_runs': 'runs',
                'rename_judges': 'judges',
                'rename_control_points': 'control_points',
                'rename_figures': 'figures',
                'rename_heat_best': 'heat_best',
                'rename_heat_average': 'heat_average',
                'rename_overall_best': 'overall_best',
                'rename_highest_average': 'highest_average'
            };
            
            for (const [inputId, columnKey] of Object.entries(renameMapping)) {
                const input = document.getElementById(inputId);
                if (input && currentColumnRenames[columnKey]) {
                    input.value = currentColumnRenames[columnKey];
                }
            }
        }
        
        function applyColumnRenames() {
            // Collect all rename values from the modal
            const renameMapping = {
                'rename_rank': 'rank',
                'rename_bib': 'bib',
                'rename_participant': 'participant',
                'rename_category': 'category',
                'rename_club': 'club',
                'rename_gender': 'gender',
                'rename_fis_code': 'fis_code',
                'rename_licence_code': 'licence_code',
                'rename_country': 'country',
                'rename_runs': 'runs',
                'rename_judges': 'judges',
                'rename_control_points': 'control_points',
                'rename_figures': 'figures',
                'rename_heat_best': 'heat_best',
                'rename_heat_average': 'heat_average',
                'rename_overall_best': 'overall_best',
                'rename_highest_average': 'highest_average'
            };
            
            currentColumnRenames = {};
            
            for (const [inputId, columnKey] of Object.entries(renameMapping)) {
                const input = document.getElementById(inputId);
                if (input && input.value.trim()) {
                    currentColumnRenames[columnKey] = input.value.trim();
                }
            }
            
            // Save to localStorage
            localStorage.setItem('columnRenames_' + <?= json_encode($selected_event) ?>, JSON.stringify(currentColumnRenames));
            
            // Apply the renames by reloading the table with rename parameters
            loadSummaryTableWithRenames();
            
            // Close modal if it exists (for backward compatibility)
            const modal = document.getElementById('columnRenameModal');
            if (modal) {
                const modalInstance = bootstrap.Modal.getInstance(modal);
                if (modalInstance) {
                    modalInstance.hide();
                }
            }
            
            const renameCount = Object.keys(currentColumnRenames).length;
            showSuccessToast(`Applied ${renameCount} column rename${renameCount !== 1 ? 's' : ''}!`);
        }
        
        function loadSummaryTableWithRenames() {
            // Get all the current filter parameters
            const url = buildSummaryTableURL();
            
            // Add column renames to the URL
            for (const [columnKey, customName] of Object.entries(currentColumnRenames)) {
                url.searchParams.append(`rename_${columnKey}`, customName);
            }
            
            // Load the table with renames
            fetch(url.toString())
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    // Apply consistent styling to summary table (same as start list)
                    let styledTableHead = data.table_head;
                    let styledTableBody = data.table_body;
                    
                    const tableContent = `
                        <div class="heat-section">
                            <div class="heat-header">
                                <h5 class="heat-title">Summary Table</h5>
                                <div class="heat-info">
                                    <span class="badge bg-primary me-2">Event ID: ${<?= json_encode($selected_event) ?>}</span>
                                    ${<?= json_encode($selected_heat) ?> ? `<span class="badge bg-info me-2">Heat: ${<?= json_encode($selected_heat) ?>}</span>` : ''}
                                    <span class="badge bg-success">${data.participant_count || 0} participants ss</span>
                                </div>
                            </div>
                            <div class="table-responsive">
                                <style>${data.table_badge_colors || ''}</style>
                                <table class="table table-striped table-hover table-sm">
                                    <thead class="table-dark">
                                        ${styledTableHead}
                                    </thead>
                                    <tbody>
                                        ${styledTableBody}
                                    </tbody>
                                </table>
                            </div>
                        </div>
                    `;
                    
                    document.getElementById('contentDisplay').innerHTML = tableContent;
                } else {
                    document.getElementById('contentDisplay').innerHTML = `
                        <div class="alert alert-warning">
                            <i class="fas fa-exclamation-triangle me-2"></i>
                            Error loading summary table: ${data.message || 'Unknown error'}
                        </div>
                    `;
                }
            })
            .catch(error => {
                console.error('Error loading summary table with renames:', error);
                showErrorToast('Error applying column renames: ' + error.message);
            });
        }
        
        function buildSummaryTableURL() {
            // Build URL with all current parameters (matching loadSummaryTable function exactly)
            const eventId = <?= json_encode($selected_event) ?>;
            const heatNumber = document.getElementById('heat_number')?.value || null;
            const categoryFilter = document.getElementById('category_filter')?.value || 'all';
            const genderFilter = document.getElementById('gender_filter_main')?.value || 'all';
            
            // Build URL string exactly like the main loadSummaryTable function
            let url = `../api/summary_table_api.php?event_id=${eventId}`;
            
            // Handle either ID-based or name-based category filter
            if (categoryFilter && categoryFilter !== 'all') {
                // Check if it's a numeric ID or a category name
                if (!isNaN(categoryFilter) && parseInt(categoryFilter) > 0) {
                    url += `&category=${categoryFilter}`;
                } else {
                    url += `&category=${encodeURIComponent(categoryFilter)}`;
                }
            } else {
                url += `&category=all`;
            }
            
            // Add heat filter if specific heat selected
            if (heatNumber && heatNumber !== '') {
                url += `&heat_run_filter={"${heatNumber}":[1,2,3]}`;
            }
            
            // Add all column visibility parameters exactly as main function does
            const showRank = document.getElementById('showRank')?.checked ?? true;
            const showBip = document.getElementById('showBip')?.checked ?? true;
            const showParticipant = document.getElementById('showParticipant')?.checked ?? true;
            const showCategory = document.getElementById('showCategory')?.checked ?? true;
            const showClub = document.getElementById('showClub')?.checked ?? true;
            const showGender = document.getElementById('showGender')?.checked ?? true;
            const showFisCode = document.getElementById('showFisCode')?.checked ?? false;
            const showLicenceCode = document.getElementById('showLicenceCode')?.checked ?? false;
            const showCountry = document.getElementById('showCountry')?.checked ?? false;
            const showRuns = document.getElementById('showRuns')?.checked ?? true;
            const showJudges = document.getElementById('showJudges')?.checked ?? false;
            const showControlPoints = document.getElementById('showControlPoints')?.checked ?? false;
            const showFigures = document.getElementById('showFigures')?.checked ?? false;
            const showEventSettings = document.getElementById('showEventSettings')?.checked ?? false;
            const showHeatBest = document.getElementById('showHeatBest')?.checked ?? true;
            const showHeatAverage = document.getElementById('showHeatAverage')?.checked ?? false;
            const showOverallBest = document.getElementById('showOverallBest')?.checked ?? false;
            const showHighestAverage = document.getElementById('showHighestAverage')?.checked ?? false;
            const sortBy = document.getElementById('sortBy')?.value ?? 'OverallAverage';
            const sortDirection = document.getElementById('sortDirection')?.value ?? 'desc';
            const genderFilter2 = document.getElementById('genderFilter')?.value ?? 'all';
            
            // Add basic column visibility
            url += `&show_rank=${showRank}`;
            url += `&show_bib=${showBip}`;
            url += `&show_participant=${showParticipant}`;
            url += `&show_category=${showCategory}`;
            url += `&show_club=${showClub}`;
            url += `&show_gender=${showGender}`;
            url += `&show_fis_code=${showFisCode}`;
            url += `&show_licence_code=${showLicenceCode}`;
            url += `&show_country=${showCountry}`;
            
            // Add aggregation column visibility
            url += `&show_runs=${showRuns}`;
            url += `&show_judges=${showJudges}`;
            url += `&show_control_points=${showControlPoints}`;
            url += `&show_figures=${showFigures}`;
            url += `&show_event_settings=${showEventSettings}`;
            
            // Add event settings detail filters
            if (showEventSettings) {
                url += `&show_format_name=${showFormatName}`;
                url += `&show_judge_info=${showJudgeInfo}`;
                url += `&show_scale_info=${showScaleInfo}`;
                url += `&show_drop_rule=${showDropRule}`;
                url += `&show_mode_config=${showModeConfig}`;
                url += `&show_heat_info=${showHeatInfo}`;
            }
            
            url += `&show_heat_best=${showHeatBest}`;
            url += `&show_heat_average=${showHeatAverage}`;
            url += `&show_overall_best=${showOverallBest}`;
            url += `&show_highest_average=${showHighestAverage}`;
            url += `&sort=${sortBy}`;
            url += `&sort_direction=${sortDirection}`;
            url += `&gender=${genderFilter2}`;
            
            return new URL(url, window.location.href);
        }
        
        function clearAllRenames() {
            // Clear all input fields in the integrated Toggle Panel
            const renameMapping = {
                'rename_rank': 'rank',
                'rename_bib': 'bib',
                'rename_participant': 'participant',
                'rename_category': 'category',
                'rename_club': 'club',
                'rename_gender': 'gender',
                'rename_fis_code': 'fis_code',
                'rename_licence_code': 'licence_code',
                'rename_country': 'country',
                'rename_runs': 'runs',
                'rename_judges': 'judges',
                'rename_control_points': 'control_points',
                'rename_figures': 'figures',
                'rename_heat_best': 'heat_best',
                'rename_heat_average': 'heat_average',
                'rename_overall_best': 'overall_best',
                'rename_highest_average': 'highest_average'
            };
            
            // Clear all input fields
            for (const inputId of Object.keys(renameMapping)) {
                const input = document.getElementById(inputId);
                if (input) {
                    input.value = '';
                }
            }
            
            // Clear the stored renames
            currentColumnRenames = {};
            
            // Remove from localStorage
            localStorage.removeItem('columnRenames_' + <?= json_encode($selected_event) ?>);
            
            // Show success message
            showSuccessToast('All column renames cleared!');
        }
        
        function loadRenamePresets(presetType) {
            // Clear all input fields first (without showing message)
            const renameMapping = {
                'rename_rank': 'rank',
                'rename_bib': 'bib',
                'rename_participant': 'participant',
                'rename_category': 'category',
                'rename_club': 'club',
                'rename_gender': 'gender',
                'rename_fis_code': 'fis_code',
                'rename_licence_code': 'licence_code',
                'rename_country': 'country',
                'rename_runs': 'runs',
                'rename_judges': 'judges',
                'rename_control_points': 'control_points',
                'rename_figures': 'figures',
                'rename_heat_best': 'heat_best',
                'rename_heat_average': 'heat_average',
                'rename_overall_best': 'overall_best',
                'rename_highest_average': 'highest_average'
            };
            
            // Clear all input fields
            for (const inputId of Object.keys(renameMapping)) {
                const input = document.getElementById(inputId);
                if (input) {
                    input.value = '';
                }
            }
            
            const presets = {
                'ski': {
                    'rename_participant': 'Skier',
                    'rename_club': 'Ski Club',
                    'rename_runs': 'Ski Runs',
                    'rename_heat_best': 'Best Ski Score',
                    'rename_heat_average': 'Average Ski Score',
                    'rename_overall_best': 'Overall Ski Average',
                    'rename_highest_average': 'Best Overall Ski'
                },
                'snowboard': {
                    'rename_participant': 'Rider',
                    'rename_club': 'Team',
                    'rename_runs': 'Runs',
                    'rename_heat_best': 'Best Run Score',
                    'rename_heat_average': 'Average Run Score',
                    'rename_overall_best': 'Overall Average',
                    'rename_highest_average': 'Best Overall'
                },
                'generic': {
                    'rename_participant': 'Athlete',
                    'rename_club': 'Team/Club',
                    'rename_bib': 'Number',
                    'rename_runs': 'Attempts',
                    'rename_heat_best': 'Best Score',
                    'rename_heat_average': 'Average Score',
                    'rename_overall_best': 'Total Average',
                    'rename_highest_average': 'Best Total'
                }
            };
            
            const preset = presets[presetType];
            if (preset) {
                for (const [inputId, value] of Object.entries(preset)) {
                    const input = document.getElementById(inputId);
                    if (input) {
                        input.value = value;
                    }
                }
                showInfoToast(`Applied ${presetType} column names preset`);
            }
        }
        
        // Global variable to store copied custom names
        let copiedCustomNames = null;
        
        function copyCustomNames() {
            // Define the mapping of input IDs to column keys
            const renameMapping = {
                'rename_rank': 'rank',
                'rename_bib': 'bib',
                'rename_participant': 'participant',
                'rename_category': 'category',
                'rename_club': 'club',
                'rename_gender': 'gender',
                'rename_fis_code': 'fis_code',
                'rename_licence_code': 'licence_code',
                'rename_country': 'country',
                'rename_runs': 'runs',
                'rename_judges': 'judges',
                'rename_control_points': 'control_points',
                'rename_figures': 'figures',
                'rename_heat_best': 'heat_best',
                'rename_heat_average': 'heat_average',
                'rename_overall_best': 'overall_best',
                'rename_highest_average': 'highest_average'
            };
            
            // Copy all current custom names from the input fields
            copiedCustomNames = {};
            let copiedCount = 0;
            
            for (const [inputId, columnKey] of Object.entries(renameMapping)) {
                const input = document.getElementById(inputId);
                if (input && input.value.trim()) {
                    copiedCustomNames[inputId] = input.value.trim();
                    copiedCount++;
                }
            }
            
            // Enable the paste button if we have copied names
            const pasteBtn = document.getElementById('pasteCustomNamesBtn');
            if (pasteBtn) {
                pasteBtn.disabled = copiedCount === 0;
            }
            
            // Show feedback message
            if (copiedCount > 0) {
                showSuccessToast(`Copied ${copiedCount} custom column name${copiedCount !== 1 ? 's' : ''}!`);
            } else {
                showInfoToast('No custom names to copy. Enter some custom names first.');
            }
        }
        
        function pasteCustomNames() {
            if (!copiedCustomNames || Object.keys(copiedCustomNames).length === 0) {
                showInfoToast('No custom names available to paste. Copy some names first.');
                return;
            }
            
            // Paste all copied custom names to the input fields
            let pastedCount = 0;
            
            for (const [inputId, value] of Object.entries(copiedCustomNames)) {
                const input = document.getElementById(inputId);
                if (input) {
                    input.value = value;
                    pastedCount++;
                }
            }
            
            // Show feedback message
            if (pastedCount > 0) {
                showSuccessToast(`Pasted ${pastedCount} custom column name${pastedCount !== 1 ? 's' : ''}!`);
            }
        }
        
        function showErrorToast(message) {
            showToast(message, 'error');
        }
        
        function showToast(message, type = 'info') {
            const bgClass = type === 'success' ? 'bg-success' : 
                          type === 'error' ? 'bg-danger' : 'bg-info';
            const iconClass = type === 'success' ? 'fa-check' : 
                             type === 'error' ? 'fa-exclamation-triangle' : 'fa-info';
                             
            const toastHtml = `
                <div class="toast align-items-center text-white ${bgClass} border-0 position-fixed" 
                     style="top: 20px; right: 20px; z-index: 9999;" role="alert" aria-live="assertive" aria-atomic="true">
                    <div class="d-flex">
                        <div class="toast-body">
                            <i class="fas ${iconClass}-circle me-2"></i>${message}
                        </div>
                        <button type="button" class="btn-close btn-close-white me-2 m-auto" data-bs-dismiss="toast"></button>
                    </div>
                </div>
            `;
            
            document.body.insertAdjacentHTML('beforeend', toastHtml);
            const toastElement = document.querySelector('.toast:last-child');
            const toast = new bootstrap.Toast(toastElement);
            toast.show();
            
            // Auto remove after hiding
            toastElement.addEventListener('hidden.bs.toast', () => {
                toastElement.remove();
            });
        }
    </script>
    
    <style>
        /* Compact Configuration List Styles */
        .config-item {
            transition: background-color 0.2s ease;
            border: none !important;
        }
        
        .config-item:hover {
            background-color: #f8f9fa !important;
        }
        
        .list-group-flush .list-group-item {
            border-width: 0 0 1px 0;
        }
        
        .list-group-flush .list-group-item:last-child {
            border-bottom-width: 0;
        }
        
        .config-item .btn {
            border-radius: 4px;
        }
        
        .config-item .dropdown-toggle {
            border: 1px solid #dee2e6;
        }
        
        .config-item .dropdown-toggle:hover {
            border-color: #adb5bd;
            background-color: #f8f9fa;
        }
        
        /* Consistent styling for both start lists and summary tables */
        .heat-section, .summary-table-section {
            border: 1px solid #dee2e6;
            border-radius: 8px;
            overflow: hidden;
            margin-bottom: 2rem;
        }
        
        .heat-header, .summary-header {
            background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);
            padding: 1rem;
            border-bottom: 1px solid #dee2e6;
        }
        
        .heat-title {
            margin: 0;
            color: #495057;
        }
        
        .heat-info, .summary-stats {
            margin-top: 0.5rem;
        }
     
        
        .badge {
            font-size: 0.8em;
        }
        
        .summary-stats .badge {
            font-size: 0.75em;
        }
        
        .form-check-label {
            font-size: 0.875rem;
            margin-left: 0.25rem;
        }
        
   
        /* Table responsive with max height */
        .table-responsive {
            max-height: 70vh;
            overflow-y: auto;
            border: 1px solid #dee2e6;
            border-radius: 6px;
        }
        
        /* Column toggle panel styling */
        #columnToggles .card-body {
            border: 2px dashed #dee2e6;
        }
        
        #columnToggles .form-check {
            margin-bottom: 0.5rem;
        }
        
        #columnToggles .text-muted {
            font-weight: 600;
            text-transform: uppercase;
            letter-spacing: 0.5px;
        }
        
        
        /* Enhanced Configuration Management Styles */
       
        
        .config-card[data-config-status="active"] .config-item {
            border-left: 4px solid #198754;
        }
        
        .config-card[data-config-status="public"] .config-item {
            border-left: 4px solid #0d6efd;
        }
        
        .config-card[data-config-status="draft"] .config-item {
            border-left: 4px solid #6c757d;
        }
        
        .config-card[data-config-status="private"] .config-item {
            border-left: 4px solid #dc3545;
        }
        
        #configSearch {
            transition: all 0.3s ease;
        }
        
        #configSearch:focus {
            box-shadow: 0 0 0 0.2rem rgba(13, 110, 253, 0.25);
            border-color: #86b7fe;
        }
        
        .config-card .badge {
            font-size: 0.7rem;
        }
        
        .config-item .dropdown-toggle {
            border: none !important;
            box-shadow: none !important;
        }
        
        .config-item .dropdown-toggle:focus {
            box-shadow: none !important;
        }
        
        /* Quick access bar styling */
        .card-header .input-group {
            border-radius: 0.375rem;
        }
        
        .card-header .dropdown-menu {
            max-height: 300px;
            overflow-y: auto;
        }
        
      
        
        /* General dropdown z-index fixes */
        .dropdown-menu {
            z-index: 1060 !important;
        }
        
        .dropdown-menu.show {
            z-index: 1060 !important;
        }
       
        
        /* Preview modal styling */
        .modal .pre {
            background-color: #f8f9fa !important;
            border: 1px solid #dee2e6;
            color: #212529;
        }
        
       
        
        /* Favorite star styling */
        .config-item .fa-star {
            filter: drop-shadow(0 0 2px rgba(255, 193, 7, 0.5));
        }
        
      
        
        #columnRenameModal .card {
            transition: all 0.3s ease;
            height: 100%;
        }
        
        #columnRenameModal .card:hover {
            transform: translateY(-2px);
            box-shadow: 0 4px 8px rgba(0,0,0,0.1);
        }
        
        #columnRenameModal .form-control:focus {
            border-color: #0d6efd;
            box-shadow: 0 0 0 0.2rem rgba(13, 110, 253, 0.25);
        }
        
        #columnRenameModal .card-header {
            font-weight: 600;
            border-bottom: 2px solid rgba(255,255,255,0.2);
        }
        
        #columnRenameModal .form-label {
            color: #495057;
            margin-bottom: 0.25rem;
        }
        
        #columnRenameModal .btn-group .btn {
            transition: all 0.3s ease;
        }
        
        #columnRenameModal .btn-group .btn:hover {
            transform: translateY(-1px);
        }
        
        /* Responsive adjustments for rename modal */
        @media (max-width: 768px) {
            #columnRenameModal .modal-dialog {
                max-width: 100%;
                margin: 0.5rem;
            }
            
            #columnRenameModal .col-lg-4,
            #columnRenameModal .col-lg-6 {
                margin-bottom: 1rem;
            }
        }
        
       
        
        #helpModal .modal-content {
            height: 90vh;
        }
        
        #helpModal .modal-body {
            padding: 0;
            height: calc(90vh - 120px);
        }
        
        #helpModal iframe {
            width: 100%;
            height: 100%;
            border: none;
        }
    </style>

    <!-- Help Modal -->
    <div class="modal fade" id="helpModal" tabindex="-1" aria-labelledby="helpModalLabel" aria-hidden="true">
        <div class="modal-dialog modal-xl modal-dialog-centered">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="helpModalLabel">
                        <i class="fas fa-question-circle me-2"></i>Start Lists & Summary Tables - Help
                    </h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <iframe src="/v2/help/event_start_list_help.html" title="Help Documentation" loading="lazy"></iframe>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
                    <a href="/v2/help/event_start_list_help.html" target="_blank" class="btn btn-outline-primary">
                        <i class="fas fa-external-link-alt me-1"></i>Open in New Tab
                    </a>
                </div>
            </div>
        </div>
    </div>

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