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


$selected_event = $_GET['event_id'] ?? null;
$selected_heat = $_GET['heat_number'] ?? null;
$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 = ?
        ORDER BY display_order ASC, name ASC
    ");
    $stmt->execute([$selected_event]);
    $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 -->
<link id="bootswatch-theme"
      href="/v2/assets/bootswatch/<?= btTheme('nameCode') ?>/bootstrap.min.css"
      rel="stylesheet">
<link rel="stylesheet" href="/v2/assets/css/backgrounds.css">
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">

    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
</head>
<style>
    td.col-figures  {
    font-size: .6em;
}
.col-figures {width: 10% !important;}
</style>
<body class="body-bg-aurora-bright">
    <?php include '../menu.php'; ?>
    
    <div class="container-fluid container-StyleScore p-4">
            <!-- event action menu. -->
<div class="row mb-3">
    <div class="col-12">
        <?php       
        $use_localStorage = true;
        $show_header = false;
        //$show_public_view = false;
        include 'event_actions_menu.php'; 
        ?>
    </div>
</div>
        <div class="row justify-content-center">
            <div class="col-12">
                <!-- Tab Navigation -->
                <div class="mb-4">
                    <ul class="nav nav-tabs" id="viewTabs" role="tablist">
                        <li class="nav-item" role="presentation">
                            <button class="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="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>

                <h2 class="mb-4">
                    <?php if ($view_type === 'summary_table'): ?>
                        <i class="fas fa-table me-2 text-success"></i>Summary Tables
                    <?php else: ?>
                        <i class="fas fa-list-ol me-2 text-primary"></i>Start Lists
                    <?php endif; ?>
                </h2>
                
                <!-- Filters -->
                <div class="border-0 shadow-none card mb-3">
                    <div class="border-0 shadow-none card-body py-2">
                        <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-md-3">
                                <label for="event_id" class="form-label mb-1 small fw-semibold">Event</label>
                                <select name="event_id" id="event_id" class="form-select form-select-sm" onchange="this.form.submit()">
                                    <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>
                            
                            <?php if ($selected_event): ?>
                            <div class="col-md-3">
                                <label for="heat_number" class="form-label mb-1 small fw-semibold">Heat (Optional)</label>
                                <select name="heat_number" id="heat_number" class="form-select form-select-sm" onchange="this.form.submit()">
                                    <option value="">-- All Heats --</option>
                                    <?php foreach ($heats as $heat): ?>
                                        <option value="<?= $heat['heat_number'] ?>" <?= $selected_heat == $heat['heat_number'] ? 'selected' : '' ?>>
                                            Heat <?= $heat['heat_number'] ?><?= $heat['heat_name'] ? ' - ' . htmlspecialchars($heat['heat_name']) : '' ?>
                                        </option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                            
                            <div class="col-md-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-md-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 if ($selected_heat): ?>
                                        <optgroup label="Main Categories for Heat <?= $selected_heat ?>">
                                            <?php foreach ($categories as $category): ?>
                                                <?php if ($category['is_main_category']): ?>
                                                    <option value="<?= $category['id'] ? $category['id'] : htmlspecialchars($category['category_name']) ?>">
                                                        <?= htmlspecialchars($category['category_name']) ?>
                                                    </option>
                                                <?php endif; ?>
                                            <?php endforeach; ?>
                                        </optgroup>
                                    <?php endif; ?>
                                    
                                    <optgroup label="Ranking Categories">
                                        <?php foreach ($categories as $category): ?>
                                            <?php if ($category['use_for_ranking'] && !$category['is_main_category']): ?>
                                                <option value="<?= $category['id'] ? $category['id'] : htmlspecialchars($category['category_name']) ?>">
                                                    <?= htmlspecialchars($category['category_name']) ?>
                                                </option>
                                            <?php endif; ?>
                                        <?php endforeach; ?>
                                    </optgroup>
                                    
                                    <?php if (!empty(array_filter($categories, function($c) { return !$c['is_main_category'] && !$c['use_for_ranking']; }))): ?>
                                        <optgroup label="Other Categories">
                                            <?php foreach ($categories as $category): ?>
                                                <?php if (!$category['is_main_category'] && !$category['use_for_ranking']): ?>
                                                    <option value="<?= $category['id'] ? $category['id'] : htmlspecialchars($category['category_name']) ?>">
                                                        <?= htmlspecialchars($category['category_name']) ?>
                                                    </option>
                                                <?php endif; ?>
                                            <?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>
                
                
                <!-- Configuration Management -->
                <?php if ($selected_event): ?>
                <div class="border-0 shadow-none card mb-3">
                    <div class="border-0 shadow-none card-body py-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>Document & Results Management</h6>
                                <small class="text-muted">Create & manage configurations for live results, PDFs, and data exports</small>
                            </div>
                            <div class="btn-group btn-group-sm" role="group">
                                <button type="button" class="btn btn-success btn-sm" onclick="showSaveConfigModal()">
                                    <i class="fas fa-plus me-1"></i>Save Current
                                </button>
                                <button type="button" class="btn btn-outline-primary btn-sm" data-bs-toggle="collapse" data-bs-target="#configPanel">
                                    <i class="fas fa-wrench me-1"></i>Settings
                                </button>
                            </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">
                                <small class="text-muted fw-semibold">Quick Load:</small>
                                <div class="input-group input-group-sm" style="max-width: 160px;">
                                    <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>
                            </div>
                            
                            <!-- Compact Configuration Cards -->
                            <div class="row g-2" id="configCards">
                                <?php foreach ($saved_configurations as $config): ?>
                                <div class="col-6 col-lg-4 config-card" data-config-name="<?= strtolower($config['name']) ?>" data-config-type="<?= $config['view_type'] ?>" data-config-status="<?= $config['status'] ?>">
                                    <div class="border-0 shadow-none card h-100 border config-item shadow-sm" data-config-id="<?= $config['id'] ?>">
                                        <div class="border-0 shadow-none card-body p-2">
                                            <div class="d-flex justify-content-between align-items-start mb-1">
                                                <?php 
                                                // Clean display name by removing document type prefixes
                                                $displayName = $config['name'];
                                                $displayName = preg_replace('/^(Start List|Summary Table)\s*-\s*/', '', $displayName);
                                                ?>
                                                <h6 class="card-title mb-0 small fw-bold text-truncate flex-grow-1 me-1" title="<?= htmlspecialchars($displayName) ?>">
                                                    <?= htmlspecialchars($displayName) ?>
                                                </h6>
                                                <div class="dropdown">
                                                    <button class="btn btn-sm btn-link text-muted p-0 lh-1" type="button" data-bs-toggle="dropdown">
                                                        <i class="fas fa-ellipsis-v"></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>
                                                        <?php if ($config['view_type'] === 'summary_table'): ?>
                                                        <li><hr class="dropdown-divider"></li>
                                                        <li><h6 class="dropdown-header">Export Formats</h6></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=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 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 class="d-flex flex-wrap gap-1 mb-1">
                                                <span class="badge bg-<?= $config['status'] === 'active' ? 'success' : ($config['status'] === 'public' ? 'primary' : 'secondary') ?>" style="font-size: 0.6rem;">
                                                    <?= ucfirst($config['status']) ?>
                                                </span>
                                                <span class="badge bg-light text-dark" style="font-size: 0.6rem;">
                                                    <?= $config['view_type'] === 'summary_table' ? 'Results' : 'Start List' ?>
                                                </span>
                                                <?php if ($config['heat_number']): ?>
                                                    <span class="badge bg-warning text-dark" style="font-size: 0.6rem;">Heat <?= $config['heat_number'] ?></span>
                                                <?php endif; ?>
                                            </div>
                                            
                                            <div class="small text-muted mb-2" style="font-size: 0.75rem;">
                                                <?php if ($config['category']): ?>
                                                    <div class="text-truncate"><i class="fas fa-tag me-1"></i><?= htmlspecialchars($config['category']) ?></div>
                                                <?php endif; ?>
                                                <div><i class="fas fa-calendar me-1"></i><?= date('M j', strtotime($config['created_at'])) ?></div>
                                            </div>
                                            
                                            <div class="d-grid">
                                                <div class="btn-group btn-group-sm" role="group">
                                                <button type="button" class="btn btn-primary btn-sm py-1" onclick="loadConfiguration(<?= $config['id'] ?>)" title="Load this configuration">
                                                    <i class="fas fa-play"></i>
                                                </button>
                                                <?php if ($config['view_type'] === 'start_list'): ?>
                                                    <button type="button" onclick="window.open('../api/start_list_api.php?event_id=<?= $selected_event ?><?= $config['heat_number'] ? '&heat_number=' . $config['heat_number'] : '' ?>&format=pdf&config_name=<?= $config['name'] ?>', '_blank')" class="btn btn-outline-danger btn-sm py-1" title="Export PDF">
                                                        <i class="fas fa-file-pdf"></i>
                                                    </button>
                                                    <button type="button" onclick="window.open('../api/start_list_api.php?event_id=<?= $selected_event ?><?= $config['heat_number'] ? '&heat_number=' . $config['heat_number'] : '' ?>&format=html&config_name=<?= $config['name'] ?>', '_blank')" class="btn btn-outline-dark btn-sm py-1" title="View HTML">
                                                        <i class="fas fa-table"></i>
                                                    </button>
                                                   
                                                <?php elseif ($config['view_type'] === 'summary_table'): ?>
                                                    <button type="button" onclick="window.open('../api/summary_table_api.php?config_id=<?= $config['id'] ?>&config_name=<?= urlencode($config['name']) ?>&format=pdf', '_blank')" class="btn btn-outline-danger btn-sm py-1" title="Export PDF">
                                                        <i class="fas fa-file-pdf"></i>
                                                    </button>
                                                    <button type="button" onclick="window.open('../api/summary_table_api.php?config_id=<?= $config['id'] ?>&config_name=<?= urlencode($config['name']) ?>&format=html', '_blank')" class="btn btn-outline-dark btn-sm py-1" title="View HTML">
                                                        <i class="fas fa-table"></i>
                                                    </button>
                                                    <button type="button" onclick="window.location.href='../api/summary_table_api.php?config_id=<?= $config['id'] ?>&config_name=<?= urlencode($config['name']) ?>&format=csv'" class="btn btn-outline-success btn-sm py-1" title="Download CSV">
                                                        <i class="fas fa-file-csv"></i>
                                                    </button>
                                                <?php endif; ?>
                                                </div>
                                            </div>
                                        </div>
                                        <?php if (isset($config['is_favorite']) && $config['is_favorite']): ?>
                                            <div class="position-absolute top-0 start-0 m-1">
                                                <i class="fas fa-star text-warning"></i>
                                            </div>
                                        <?php endif; ?>
                                    </div>
                                </div>
                                <?php endforeach; ?>
                            </div>
                        </div>
                        <?php endif; ?>
                    </div>
                    
                    <div class="collapse" id="configPanel">
                        <div class="border-0 shadow-none card-body py-2 bg-light">
                            <div class="d-flex justify-content-between align-items-center mb-2">
                                <h6 class="mb-0 text-primary"><i class="fas fa-plus-circle me-2"></i>Save Current Settings as New Configuration</h6>
                                <small class="text-muted">Saves current filters & view settings for reuse</small>
                            </div>
                            <!-- Save Current Configuration -->
                            <div class="row g-2">
                                <div class="col-md-4">
                                    <label for="configName" class="form-label small fw-semibold">Configuration Name</label>
                                    <input type="text" id="configName" class="form-control form-control-sm" 
                                           placeholder="Enter configuration name">
                                    <div class="form-text small">
                                        <span id="suggestedName" class="text-muted"></span>
                                    </div>
                                </div>
                                <div class="col-md-2">
                                    <label for="configStatus" class="form-label small fw-semibold">Status</label>
                                    <select id="configStatus" 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="configOrder" class="form-label small fw-semibold">Order</label>
                                    <input type="number" id="configOrder" class="form-control form-control-sm" value="0" min="0">
                                </div>
                                <div class="col-md-4">
                                    <label class="form-label small fw-semibold">&nbsp;</label>
                                    <div class="d-flex gap-1">
                                        <button type="button" class="btn btn-success btn-sm" onclick="saveCurrentConfiguration()">
                                            <i class="fas fa-save me-1"></i>Save
                                        </button>
                                        <button type="button" class="btn btn-outline-info btn-sm" onclick="generateConfigName()">
                                            <i class="fas fa-magic me-1"></i>Auto-Name
                                        </button>
                                    </div>
                                </div>
                            </div>

                           
                        </div>
                    </div>
                </div>
                <?php endif; ?>
                <?php if ($selected_event): ?>
                
                <!-- Content Display -->
                <div class="border-0 shadow-none card">
                    <div class="border-0 shadow-none card-body py-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 ($selected_heat): ?>
                                        - Heat <?= $selected_heat ?>
                                    <?php endif; ?>
                                </h6>


                                        <!-- Action Buttons -->
                                <div class="actions">
                                    <?php if ($view_type === 'start_list'): ?>
                                            <!-- Start List Actions -->
                                            <div class="d-flex flex-wrap gap-1">
                                                
                                                <button type="button" class="btn btn-outline-secondary btn-sm" onclick="refreshContent()">
                                                    <i class="fas fa-refresh me-1"></i>Refresh
                                                </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-sm btn-outline-info" onclick="showColumnRenameModal()">
                                                            <i class="fas fa-edit me-1"></i>Rename Columns
                                                        </button>
                                                    </div>
                                                </div>
                                                
                                            
                                            </div>
                                    <?php endif; ?>
                                        
                                </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-eye me-2"></i>Column Visibility</h6>
                                                       
                                                    </div>
                                                    <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="loadSummaryTable()">
                                                                <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="loadSummaryTable()">
                                                                <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="loadSummaryTable()">
                                                                <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="loadSummaryTable()">
                                                                <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="loadSummaryTable()">
                                                                <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="loadSummaryTable()">
                                                                <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="loadSummaryTable()">
                                                                <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="loadSummaryTable()">
                                                                <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="loadSummaryTable()">
                                                                <label class="form-check-label" for="showCountry">Country Code</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="loadSummaryTable()">
                                                                <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="loadSummaryTable()">
                                                                <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="loadSummaryTable()">
                                                                <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="loadSummaryTable()">
                                                                <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="loadSummaryTable()">
                                                                <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="loadSummaryTable()">
                                                                <label class="form-check-label" for="showHeatAverage">Heat Average</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="loadSummaryTable()">
                                                                <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="loadSummaryTable()">
                                                                <label class="form-check-label" for="showHighestAverage">Overall Best</label>
                                                            </div>
                                                        </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="loadSummaryTable()">
                                                                <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="loadSummaryTable()">
                                                                <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="loadSummaryTable()">
                                                                <option value="all">All Genders</option>
                                                                <option value="M">Male</option>
                                                                <option value="F">Female</option>
                                                            </select>
                                                        </div>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                   
                        </div>
                    
                    <div class="border-0 shadow-none card-body">
                        <div id="contentDisplay">
                            <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 content...</p>
                            </div>
                        </div>
                    </div>
                </div>
                <?php else: ?>
                <div class="border-0 shadow-none card">
                    <div class="border-0 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>
    
    <!-- Edit Configuration Modal -->
    <div class="modal fade" 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-xl 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="border-0 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="border-0 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="border-0 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="border-0 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="border-0 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="border-0 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>

    <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);
            }
            
            <?php if ($selected_event): ?>
                loadContent();
            <?php endif; ?>
        });
        
        function switchView(viewType) {
            const url = new URL(window.location);
            url.searchParams.set('view_type', viewType);
            window.location.href = url.toString();
        }
        
        function loadContent() {
            if (currentViewType === 'summary_table') {
                loadSummaryTable();
            } else {
                loadStartList();
            }
        }
        
        function loadStartList() {
            const eventId = <?= json_encode($selected_event) ?>;
            const heatNumber = <?= json_encode($selected_heat) ?>;
            const genderFilter = document.getElementById('gender_filter_main')?.value ?? 'all';
            
            if (!eventId) return;
            
            let url = `../api/start_list_api.php?event_id=${eventId}${heatNumber ? '&heat_number=' + heatNumber : ''}&format=html`;
            
            // Add gender filter
            if (genderFilter && genderFilter !== 'all') {
                url += `&gender=${genderFilter}`;
            }
            
            fetch(url)
                .then(response => response.text())
                .then(html => {
                    document.getElementById('contentDisplay').innerHTML = html;
                })
                .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 heatNumber = <?= json_encode($selected_heat) ?>;
            
            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;
            
            // Aggregation 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;
            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 genderFilter = document.getElementById('genderFilter')?.value ?? 'all';
            const categoryFilter = document.getElementById('category_filter')?.value ?? 'all';
            
            // Build URL parameters
            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) {
                url += `&heat_run_filter={"${heatNumber}":[1,2,3]}`;
            }
            
            // 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_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}`;
            
            // Add column renames if they exist
            if (currentColumnRenames && Object.keys(currentColumnRenames).length > 0) {
                for (const [columnKey, customName] of Object.entries(currentColumnRenames)) {
                    url += `&rename_${columnKey}=${encodeURIComponent(customName)}`;
                }
            }
            
            fetch(url)
                .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;
                        
                        // 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">
                                    <table class="table table-striped table-hover">
                                        ${styledTableHead || ''}
                                        ${styledTableBody || ''}
                                    </table>
                                </div>
                            </div>
                        `;
                        document.getElementById('contentDisplay').innerHTML = tableContent;
                    } else {
                        document.getElementById('contentDisplay').innerHTML = `
                            <div class="alert alert-danger">
                                <i class="fas fa-exclamation-triangle me-2"></i>
                                Error loading summary table: ${data.message || 'Unknown error'}
                            </div>
                        `;
                    }
                })
                .catch(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>
                    `;
                });
        }
        
 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 = <?= json_encode($selected_heat) ?>;
            const categoryFilter = document.getElementById('category_filter')?.value ?? 'all';
            
            let url = `../api/summary_table_api.php?event_id=${eventId}&category=${categoryFilter}&format=json`;
            if (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();
        }
        // Configuration Management Functions
        function generateConfigName() {
            const eventId = <?= json_encode($selected_event) ?>;
            const eventName = document.querySelector('#event_id option:checked')?.text || 'Event';
            const heatNumber = <?= json_encode($selected_heat) ?>;
            const heatText = heatNumber ? ` - Heat ${heatNumber}` : '';
            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}`;
            
            document.getElementById('configName').value = suggestedName;
            document.getElementById('suggestedName').textContent = `Suggested: ${suggestedName}`;
        }
        
        function getCurrentConfiguration() {
            if (currentViewType === 'summary_table') {
                return {
                    view_type: 'summary_table',
                    event_id: <?= json_encode($selected_event) ?>,
                    heat_number: <?= json_encode($selected_heat) ?>,
                    category: document.getElementById('category_filter')?.value || 'all',
                    filters: {
                        // 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,
                        
                        // Aggregation columns
                        showRuns: document.getElementById('showRuns')?.checked ?? true,
                        showJudges: document.getElementById('showJudges')?.checked ?? false,
                        showControlPoints: document.getElementById('showControlPoints')?.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,
                        sortBy: document.getElementById('sortBy')?.value ?? 'OverallAverage',
                        sortDirection: document.getElementById('sortDirection')?.value ?? 'desc',
                        genderFilter: document.getElementById('genderFilter')?.value ?? 'all',
                        
                        // Column renames
                        columnRenames: currentColumnRenames || {}
                    }
                };
            } else {
                return {
                    view_type: 'start_list',
                    event_id: <?= json_encode($selected_event) ?>,
                    heat_number: <?= json_encode($selected_heat) ?>,
                    category: null,
                    filters: {
                        genderFilter: document.getElementById('gender_filter_main')?.value ?? 'all',
                        
                        // Column renames (can be used for start lists too)
                        columnRenames: currentColumnRenames || {}
                    }
                };
            }
        }
        
        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 configuration = getCurrentConfiguration();
            
            const data = {
                name: configName,
                view_type: configuration.view_type,
                event_id: configuration.event_id,
                heat_number: configuration.heat_number,
                category: configuration.category,
                configuration: configuration.filters,
                display_order: configOrder,
                status: configStatus
            };
            
            fetch('../api/result_configurations_api.php?action=save', {
                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) {
            fetch(`../api/result_configurations_api.php?action=get&id=${configId}`)
            .then(response => response.json())
            .then(result => {
                if (result.success) {
                    const config = result.data;

                    // Switch to the correct view type if needed
                    if (config.view_type !== currentViewType) {
                        switchView(config.view_type);
                        return;
                    }

                    // Set heat_number, gender_filter_main, category_filter from configuration
                    if (config.heat_number !== undefined && document.getElementById('heat_number')) {
                        document.getElementById('heat_number').value = config.heat_number || '';
                    }
                    if (config.configuration?.genderFilter && document.getElementById('gender_filter_main')) {
                        document.getElementById('gender_filter_main').value = config.configuration.genderFilter;
                    }
                    if (config.category && document.getElementById('category_filter')) {
                        document.getElementById('category_filter').value = config.category;
                    }

                    // 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 with the new configuration applied
                    loadContent();

                    // Close the config panel
                    const configPanel = new bootstrap.Collapse(document.getElementById('configPanel'));
                    configPanel.hide();

                } else {
                    alert('Error loading configuration: ' + result.message);
                }
            })
            .catch(error => {
                alert('Error loading configuration: ' + error.message);
            });
        }
        
        function applyConfigurationToSummaryTable(filters) {
            try {
                console.log('Applying configuration to summary table:', filters);
                
                // 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'],
                    'showRuns': ['showRuns', 'show_runs'],
                    'showJudges': ['showJudges', 'show_judges'],
                    'showControlPoints': ['showControlPoints', 'show_control_points'],
                    'showFigures': ['showFigures', 'show_figures'],
                    '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 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 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);
                }

                console.log('Configuration applied successfully');
            } catch (error) {
                console.error('Error applying configuration:', error);
            }
        }
        
        function applyConfigurationToStartList(filters) {
            // Apply start list filter settings
            if (document.getElementById('gender_filter_main')) {
                document.getElementById('gender_filter_main').value = filters.genderFilter ?? 'all';
            }
        }
        
        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');
            el.textContent = msg || 'Unknown error';
            el.classList.remove('d-none');
        }
        function hideEditError() {
            const el = document.getElementById('editConfigAlert');
            el.textContent = '';
            el.classList.add('d-none');
        }

        function editConfiguration(configId) {
            hideEditError();
            editConfigId = configId;

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

                // Fill fields
                document.getElementById('editConfigName').value = cfg.name || '';
                document.getElementById('editConfigStatus').value = cfg.status || 'draft';
                document.getElementById('editConfigOrder').value = Number(cfg.display_order || 0);
                document.getElementById('editConfigViewType').value = cfg.view_type || ''; // readonly field already present
                document.getElementById('editConfigHeat').value = cfg.heat_number ?? '';
                document.getElementById('editConfigCategory').value = (cfg.category && cfg.category !== '') ? cfg.category : 'all';

                let filters = cfg.configuration || {};
                if (typeof filters === 'string') {
                    try { filters = JSON.parse(filters); } catch(_) {}
                }
                document.getElementById('editConfigFilters').value = JSON.stringify(filters || {}, null, 2);

                const modalEl = document.getElementById('editConfigModal');
                editConfigModalInstance = editConfigModalInstance || new bootstrap.Modal(modalEl);
                editConfigModalInstance.show();
            })
            .catch(err => {
                alert('Error loading 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();
        }
        
        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() {
            generateConfigName();
            const configPanel = document.getElementById('configPanel');
            if (configPanel.classList.contains('show')) {
                configPanel.classList.remove('show');
            } else {
                const collapse = new bootstrap.Collapse(configPanel);
                collapse.show();
            }
            
            // Focus on the config name input
            setTimeout(() => {
                document.getElementById('configName')?.focus();
            }, 300);
        }
        
        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 showColumnRenameModal() {
            loadCurrentRenames();
            const modal = new bootstrap.Modal(document.getElementById('columnRenameModal'));
            modal.show();
        }
        
        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 and show success message
            const modal = bootstrap.Modal.getInstance(document.getElementById('columnRenameModal'));
            modal.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</span>
                                </div>
                            </div>
                            <div class="table-responsive">
                                <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 = <?= json_encode($selected_heat) ?>;
            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) {
                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 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_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 modal
            const inputs = document.querySelectorAll('#columnRenameModal input[type="text"]');
            inputs.forEach(input => {
                input.value = '';
            });
        }
        
        function loadRenamePresets(presetType) {
            clearAllRenames();
            
            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`);
            }
        }
        
        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>
        /* 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;
        }
        
        /* Apply consistent table styling */
        .table th {
            background-color: #343a40 !important;
            color: white !important;
            border-color: #454d55 !important;
            white-space: nowrap;
            position: sticky;
            top: 0;
            z-index: 10;
        }
        
        .table td {
            border-color: #dee2e6;
        }
        
        .table-striped > tbody > tr:nth-of-type(odd) > td {
            background-color: rgba(0,0,0,.05);
        }
        
        .table-hover > tbody > tr:hover > td {
            background-color: rgba(0,0,0,.075);
        }
        
        .badge {
            font-size: 0.8em;
        }
        
        .summary-stats .badge {
            font-size: 0.75em;
        }
        
        .form-check-label {
            font-size: 0.875rem;
            margin-left: 0.25rem;
        }
        
        .nav-tabs .nav-link {
            border-radius: 6px 6px 0 0;
        }
        
        .nav-tabs .nav-link.active {
            background-color: #fff;
            border-color: #dee2e6 #dee2e6 #fff;
        }
        
        /* 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;
        }
        
        /* Responsive adjustments */
        @media (max-width: 768px) {
            .table-responsive {
                font-size: 0.8rem;
            }
            
            .badge {
                font-size: 0.7em;
            }
            
            .btn {
                padding: 0.375rem 0.5rem;
                font-size: 0.875rem;
            }
        }

        /* Enhanced Configuration Management Styles */
        .config-item {
            transition: all 0.3s ease;
            cursor: pointer;
            position: relative;
        }
        
        .config-item:hover {
            transform: translateY(-2px);
            box-shadow: 0 4px 12px rgba(0,0,0,0.15);
            border-color: #0d6efd !important;
        }
        
        .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;
        }
        
        /* Animation for config cards filtering */
        .config-card {
            transition: opacity 0.3s ease, transform 0.3s ease;
                z-index: 5;
        }
        
        .config-card[style*="display: none"] {
            opacity: 0;
            transform: scale(0.8);
        }
        
        /* Preview modal styling */
        .modal .pre {
            background-color: #f8f9fa !important;
            border: 1px solid #dee2e6;
            color: #212529;
        }
        
        /* Toast notifications */
        .toast {
            min-width: 300px;
        }
        
        /* Favorite star styling */
        .config-item .fa-star {
            filter: drop-shadow(0 0 2px rgba(255, 193, 7, 0.5));
        }
        
        /* Column Rename Modal Styling */
        #columnRenameModal .modal-dialog {
            
        }
        
        #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;
            }
        }
    </style>
</body>
</html>