<?php
include '../includes/auth.php';
include '../includes/db.php';
///
// https://sortablejs.github.io/Sortable/
///
// Define selected_event first
$selected_event = $_GET['event_id'] ?? null;

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

// Fetch filters - get categories from event_participants for selected event
$categories = [];
$genders = $pdo->query("SELECT DISTINCT gender FROM participants ORDER BY gender")->fetchAll(PDO::FETCH_COLUMN);
$clubs = $pdo->query("SELECT DISTINCT club FROM participants ORDER BY club")->fetchAll(PDO::FETCH_COLUMN);
$years = $pdo->query("SELECT DISTINCT YEAR(date_of_birth) as year FROM participants ORDER BY year DESC")->fetchAll(PDO::FETCH_COLUMN);

// Get categories specific to the selected event from event_participants
if ($selected_event) {
    $categories_stmt = $pdo->prepare("SELECT DISTINCT category FROM event_participants WHERE event_id = ? AND category IS NOT NULL ORDER BY category");
    $categories_stmt->execute([$selected_event]);
    $categories = $categories_stmt->fetchAll(PDO::FETCH_COLUMN);
}

// Load participants - show those assigned to event but not in any heat
if ($selected_event) {
$stmt = $pdo->prepare("
    SELECT DISTINCT p.id, p.bib, p.first_name, p.last_name, p.club, p.gender, p.date_of_birth,
           COALESCE(ep_cat.category, p.category) as category,
           0 as assignment_count,
           NULL as assigned_heats
    FROM participants p
    INNER JOIN participants_event pe ON p.id = pe.participant_id AND pe.event_id = ?
    LEFT JOIN event_participants ep ON p.id = ep.participant_id AND ep.event_id = ?
    LEFT JOIN event_participants ep_cat ON p.id = ep_cat.participant_id AND ep_cat.event_id = ? AND ep_cat.category IS NOT NULL
    WHERE ep.id IS NULL
    ORDER BY p.bib ASC
");
$stmt->execute([$selected_event, $selected_event, $selected_event]);
    $participants = $stmt->fetchAll(PDO::FETCH_ASSOC);
} else {
    // If no event selected, show all participants with their base category
    $participants = $pdo->query("SELECT id, bib, first_name, last_name, club, category, gender, date_of_birth, 0 as assignment_count, NULL as assigned_heats FROM participants ORDER BY first_name ASC")->fetchAll(PDO::FETCH_ASSOC);
}

// Assign logic
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['assign_participants'])) {
    $event_id = $_POST['event_id'];
    $heat_number = $_POST['heat_number'];
    $participants_to_assign = $_POST['participant_ids'] ?? [];

    foreach ($participants_to_assign as $participant_id) {
        if (!$participant_id) continue;

        $bib_check = $pdo->prepare("
            SELECT COUNT(*) FROM event_participants ep
            JOIN participants p ON ep.participant_id = p.id
            WHERE ep.event_id = ? AND ep.heat_number = ? AND p.bib = (
                SELECT bib FROM participants WHERE id = ?
            )
        ");
        $bib_check->execute([$event_id, $heat_number, $participant_id]);
        if ($bib_check->fetchColumn() == 0) {
            $stmt = $pdo->prepare("INSERT INTO event_participants (event_id, participant_id, heat_number) VALUES (?, ?, ?)");
            $stmt->execute([$event_id, $participant_id, $heat_number]);
        }
    }
}

// Delete single
if (isset($_GET['delete_id'])) {
    // Get participant_id and event_id before deleting
    $stmt = $pdo->prepare("SELECT participant_id, event_id FROM event_participants WHERE id = ?");
    $stmt->execute([(int)$_GET['delete_id']]);
    $assignment = $stmt->fetch();
    
    if ($assignment) {
        // Delete from event_participants
        $pdo->prepare("DELETE FROM event_participants WHERE id = ?")->execute([(int)$_GET['delete_id']]);
        
        // Also remove from participants_event
       // $pdo->prepare("DELETE FROM participants_event WHERE participant_id = ? AND event_id = ?")->execute([
       //     $assignment['participant_id'], 
       //     $assignment['event_id']
       // ]);
    }
    
    header("Location: heats_configure.php?event_id=" . (int)$_GET['event_id']);
    exit;
}

// Bulk delete
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['bulk_delete'])) {
    $ids = $_POST['delete_ids'] ?? [];
    if ($ids) {
        // Get all participant_id and event_id pairs before deleting
        $placeholders = implode(',', array_fill(0, count($ids), '?'));
        $stmt = $pdo->prepare("SELECT participant_id, event_id FROM event_participants WHERE id IN ($placeholders)");
        $stmt->execute($ids);
        $assignments = $stmt->fetchAll(PDO::FETCH_ASSOC);
        
        // Delete from event_participants
        $in = implode(',', array_fill(0, count($ids), '?'));
        $pdo->prepare("DELETE FROM event_participants WHERE id IN ($in)")->execute($ids);
        
        // Also remove from participants_event for each assignment
        //foreach ($assignments as $assignment) {
        //    $pdo->prepare("DELETE FROM participants_event WHERE participant_id = ? AND event_id = ?")->execute([
        //        $assignment['participant_id'], 
        //        $assignment['event_id']
        //    ]);
        //}
    }
    header("Location: heats_configure.php?event_id=" . (int)$_GET['event_id']);
    exit;
}

// Auto assign
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['auto_assign'])) {
    $event_id = $_GET['event_id'];
    $heat_number = $_POST['auto_heat'];
    $ids = explode(',', $_POST['filtered_ids']);
    foreach ($ids as $participant_id) {
        $bib_check = $pdo->prepare("
            SELECT COUNT(*) FROM event_participants ep
            JOIN participants p ON ep.participant_id = p.id
            WHERE ep.event_id = ? AND ep.heat_number = ? AND p.bib = (
                SELECT bib FROM participants WHERE id = ?
            )
        ");
        $bib_check->execute([$event_id, $heat_number, $participant_id]);
        if ($bib_check->fetchColumn() == 0) {
            $stmt = $pdo->prepare("INSERT INTO event_participants (event_id, participant_id, heat_number) VALUES (?, ?, ?)");
            $stmt->execute([$event_id, $participant_id, $heat_number]);
        }
    }
    header("Location: heats_configure.php?event_id=" . $event_id);
    exit;
}

// Current assignments
$assignments = [];
$selected_event = $_GET['event_id'] ?? null;
$heat_filter = $_GET['heat_filter'] ?? null;
// Current assignments - get bib from event_participants.bib_number
if ($selected_event) {
    $query = "
        SELECT ep.id, ep.heat_number, ep.bib_number as bib, ep.category, 
               p.first_name, p.last_name, p.club, p.gender, p.date_of_birth, p.id as participant_id
        FROM event_participants ep
        JOIN participants p ON ep.participant_id = p.id
        WHERE ep.event_id = ?
    ";
    
    if ($heat_filter) {
        $query .= " AND ep.heat_number = ? ORDER BY ep.sort_order ASC, ep.bib_number ASC";
        $stmt = $pdo->prepare($query);
        $stmt->execute([$selected_event, $heat_filter]);
    } else {
        $query .= " ORDER BY ep.sort_order ASC, ep.bib_number ASC";
        $stmt = $pdo->prepare($query);
        $stmt->execute([$selected_event]);
    }
    $assignments = $stmt->fetchAll(PDO::FETCH_ASSOC);
}



    // Get bib series
    $stmt = $pdo->prepare("SELECT * FROM bib_series WHERE event_id = ? ORDER BY id ASC");
    $stmt->execute([$selected_event]);
    $bib_series = $stmt->fetchAll(PDO::FETCH_ASSOC);

?>
<!DOCTYPE html>
<html>
<head>
    <title>Configure Heats</title>
    <?php include_once '../includes/stylesheets.php'; ?>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://code.jquery.com/ui/1.13.2/jquery-ui.min.js"></script>
    

<script>
    function collectFiltered() {
        let visible = Array.from(document.querySelectorAll('#participantSelect option'))
            .filter(opt => opt.style.display !== 'none')
            .map(opt => opt.value);
        document.getElementById('autoFilteredIDs').value = visible.join(',');
    }
    </script>
</head>
<body class="body-bg-aurora-bright">
    <?php include '../menu.php'; ?>
<div class="container p-2">
    <!-- event action menu. -->
    <div class="row mb-2">
        <div class="col-12">
            <?php       
            $use_localStorage = true;
            $show_header = false;
            //$show_public_view = false;
            include 'event_actions_menu.php'; 
            ?>
        </div>
    </div>
    <h4 class="mb-2">Assign Participants to Heats</h4>
    <form method="get" class="card border mb-2 load-event-selection">
        <div class="card-body p-2">
            <div class="row align-items-center">
                <div class="col-md-2">
                    <label class="form-label small fw-bold mb-0">Event:</label>
                </div>
                <div class="col-md-8">
                    <select name="event_id" class="form-select form-select-sm" onchange="this.form.submit()" required>
                        <option value="">-- Choose Event --</option>
                        <?php foreach ($events as $event): ?>
                            <option value="<?= $event['id'] ?>" <?= $selected_event == $event['id'] ? 'selected' : '' ?>>
                                <?= htmlspecialchars($event['name']) ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>
            </div>
        </div>
    </form>

      <?php if ($selected_event): ?>
        <?php if ($selected_event): ?>
            
        <!-- Assignment Form -->
        <div class="card mb-2">
            <div class="card-header bg-light py-2">
                <h6 class="mb-0">
                    <i class="fas fa-user-plus me-1 text-success"></i>Assign Participants to Heat
                </h6>
                <small class="text-muted">Select a heat and participants to assign them quickly</small>
            </div>
            <div class="card-body p-2">
                <form method="post" id="ajaxAssignForm" data-event="<?= $selected_event ?>">
                    <input type="hidden" name="event_id" value="<?= $selected_event ?>">
                    <input type="hidden" name="assign_participants" value="1">
                    
                    <div class="row g-2">
                        
                        
                        <!-- Filters Section -->
                        <div class="col-lg-12">
                            <label class="form-label small fw-bold">
                                <i class="fas fa-filter me-1 text-info"></i>Filter Participants
                            </label>
                            <div class="row g-1 mb-2">
                                <div class="col-md-3">
                                    <select id="categoryFilter" class="form-select form-select-sm" onchange="filterParticipants()">
                                        <option value="">All Categories</option>
                                        <?php 
                                        // Get categories from participants available for assignment
                                        $available_categories = array_unique(array_filter(array_column($participants, 'category')));
                                        sort($available_categories);
                                        foreach ($available_categories as $c): ?>
                                            <option value="<?= htmlspecialchars($c) ?>"><?= htmlspecialchars($c) ?></option>
                                        <?php endforeach; ?>
                                    </select>
                                </div>
                                <div class="col-md-3">
                                    <select id="genderFilter" class="form-select form-select-sm" onchange="filterParticipants()">
                                        <option value="">All Genders</option>
                                        <?php foreach ($genders as $g): ?>
                                            <option value="<?= htmlspecialchars($g) ?>"><?= htmlspecialchars($g) ?></option>
                                        <?php endforeach; ?>
                                    </select>
                                </div>
                                <div class="col-md-3">
                                    <select id="clubFilter" class="form-select form-select-sm" onchange="filterParticipants()">
                                        <option value="">All Clubs</option>
                                        <?php foreach ($clubs as $c): ?>
                                            <option value="<?= htmlspecialchars($c) ?>"><?= htmlspecialchars($c) ?></option>
                                        <?php endforeach; ?>
                                    </select>
                                </div>
                                <div class="col-md-3">
                                    <select id="yearFilter" class="form-select form-select-sm" onchange="filterParticipants()">
                                        <option value="">All Years</option>
                                        <?php 
                                        // Get years from participants data instead of database query
                                        $participantYears = array_unique(array_filter(array_map(function($p) {
                                            return $p['date_of_birth'] ? date('Y', strtotime($p['date_of_birth'])) : null;
                                        }, $participants)));
                                        rsort($participantYears);
                                        
                                        foreach ($participantYears as $y): ?>
                                            <option value="<?= $y ?>"><?= $y ?></option>
                                        <?php endforeach; ?>
                                    </select>
                                </div>
                            </div>
                            
                            <!-- Participant Selection -->
<div class="participant-selection-wrapper">
    <div class="d-flex justify-content-between align-items-center mb-1">
        <label class="form-label small fw-bold mb-0">
            <i class="fas fa-users me-1 text-warning"></i>Available Participants
            <span id="participantStatusBadge" class="badge bg-info ms-1">0 selected</span>
        </label>
        <div class="d-flex gap-1">
            <!-- View Toggle Buttons -->
            <div class="btn-group btn-group-sm" role="group" aria-label="View Toggle">
                <button type="button" class="btn btn-outline-secondary active btn-sm" id="gridViewBtn" onclick="switchToGridView()">
                    <i class="fas fa-th"></i>
                </button>
                <button type="button" class="btn btn-outline-secondary btn-sm" id="rowViewBtn" onclick="switchToRowView()">
                    <i class="fas fa-list"></i>
                </button>
            </div>
            
            <div class="btn-group btn-group-sm">
                <button type="button" class="btn btn-outline-primary btn-sm" onclick="selectAllVisible()">
                    <i class="fas fa-check-double"></i>
                </button>
                <button type="button" class="btn btn-outline-secondary btn-sm" onclick="clearSelection()">
                    <i class="fas fa-times"></i>
                </button>
            </div>
        </div>
    </div>
    
    <!-- Search Bar -->
    <div class="mb-2">
        <div class="input-group input-group-sm">
            <span class="input-group-text">
                <i class="fas fa-search"></i>
            </span>
            <input type="text" id="participantSearch" class="form-control" placeholder="Search by name, bib, or club..." onkeyup="searchParticipants()">
            <button class="btn btn-outline-secondary" type="button" onclick="clearSearch()">
                <i class="fas fa-times"></i>
            </button>
        </div>
    </div>
    
    <!-- Hidden select for form submission -->
    <select name="participant_ids[]" id="participantSelect" multiple style="display: none;">
        <?php foreach ($participants as $p): ?>
            <option value="<?= $p['id'] ?>" 
                    data-category="<?= htmlspecialchars($p['category'] ?? '') ?>" 
                    data-gender="<?= htmlspecialchars($p['gender'] ?? '') ?>" 
                    data-club="<?= htmlspecialchars($p['club'] ?? '') ?>" 
                    data-date_of_birth="<?= $p['date_of_birth'] ?? '' ?>"
                    data-year="<?= $p['date_of_birth'] ? date('Y', strtotime($p['date_of_birth'])) : '' ?>"
                    data-assigned="<?= $p['assignment_count'] ?>"
                    data-heats="<?= htmlspecialchars($p['assigned_heats'] ?? '') ?>">
            </option>
        <?php endforeach; ?>
    </select>
    
    <!-- Participant Display Container -->
    <div class="participant-display-container">
        <!-- Grid View (Card-based) -->
        <div id="participantGridView" class="participant-grid-container">
            <div id="participantGrid" class="participant-grid">
                <?php foreach ($participants as $p): ?>
                    <div class="participant-card-item" 
                         data-id="<?= $p['id'] ?>"
                         data-category="<?= htmlspecialchars($p['category'] ?? '') ?>" 
                         data-gender="<?= htmlspecialchars($p['gender'] ?? '') ?>" 
                         data-club="<?= htmlspecialchars($p['club'] ?? '') ?>" 
                         data-date_of_birth="<?= $p['date_of_birth'] ?? '' ?>"
                         data-year="<?= $p['date_of_birth'] ? date('Y', strtotime($p['date_of_birth'])) : '' ?>"
                         data-assigned="<?= $p['assignment_count'] ?>"
                         data-heats="<?= htmlspecialchars($p['assigned_heats'] ?? '') ?>"
                         data-search-text="<?= strtolower($p['first_name'] . ' ' . $p['last_name'] . ' ' . $p['bib'] . ' ' . ($p['club'] ?? '')) ?>"
                         onclick="toggleParticipantSelection(this)">
                        
                        <div class="participant-card-header">
                            <div class="participant-bib-badge">
                                <?= htmlspecialchars($p['bib']) ?>
                            </div>
                            <div class="participant-selection-indicator">
                                <i class="fas fa-check"></i>
                            </div>
                            <?php if ($p['assignment_count'] > 0): ?>
                                <div class="assignment-indicator">
                                    <i class="fas fa-fire"></i>
                                    <span><?= $p['assigned_heats'] ?></span>
                                </div>
                            <?php endif; ?>
                        </div>
                        
                        <div class="participant-card-body">
                            <div class="participant-name">
                                <?= htmlspecialchars($p['first_name'] . ' ' . $p['last_name']) ?> <div class="row-id">ID: <?= $p['id'] ?></div>
                            </div>
                            
                            <div class="participant-details-grid">
                                <div class="detail-badge club">
                                    <i class="fas fa-building"></i>
                                    <span><?= htmlspecialchars($p['club'] ?? 'No Club') ?></span>
                                </div>
                                
                                <div class="detail-badge category">
                                    <i class="fas fa-tag"></i>
                                    <span><?= htmlspecialchars($p['category'] ?? 'No Category') ?></span>
                                </div>
                                
                                <div class="detail-badge gender gender-<?= $p['gender'] === 'M' ? 'male' : 'female' ?>">
                                    <i class="fas fa-<?= $p['gender'] === 'M' ? 'male' : 'female' ?>"></i>
                                    <span><?= htmlspecialchars($p['gender'] ?? '') ?></span>
                                </div>
                                
                                <?php if ($p['date_of_birth']): ?>
                                    <div class="detail-badge year">
                                        <i class="fas fa-calendar"></i>
                                        <span><?= date('Y', strtotime($p['date_of_birth'])) ?></span>
                                    </div>
                                <?php endif; ?>
                            </div>
                        </div>
                    </div>
                <?php endforeach; ?>
            </div>
        </div>
        
        <!-- Row View (Table-like) -->
        <div id="participantRowView" class="participant-row-container" style="display: none;">
            <div class="participant-row-header">
                <div class="row-header-item bib-col">bib</div>
                <div class="row-header-item name-col">Name</div>
                <div class="row-header-item club-col">Club</div>
                <div class="row-header-item category-col">Category</div>
                <div class="row-header-item gender-col">Gender</div>
                <div class="row-header-item year-col">Year</div>
                <div class="row-header-item status-col">Status</div>
                <div class="row-header-item actions-col">Actions</div>
            </div>
            
            <div id="participantRows" class="participant-rows">
                <?php foreach ($participants as $p): ?>
                    <div class="participant-row-item" 
                         data-id="<?= $p['id'] ?>"
                         data-category="<?= htmlspecialchars($p['category'] ?? '') ?>" 
                         data-gender="<?= htmlspecialchars($p['gender'] ?? '') ?>" 
                         data-club="<?= htmlspecialchars($p['club'] ?? '') ?>" 
                         data-date_of_birth="<?= $p['date_of_birth'] ?? '' ?>"
                         data-year="<?= $p['date_of_birth'] ? date('Y', strtotime($p['date_of_birth'])) : '' ?>"
                         data-assigned="<?= $p['assignment_count'] ?>"
                         data-heats="<?= htmlspecialchars($p['assigned_heats'] ?? '') ?>"
                         data-search-text="<?= strtolower($p['first_name'] . ' ' . $p['last_name'] . ' ' . $p['bib'] . ' ' . ($p['club'] ?? '')) ?>"
                         onclick="toggleParticipantSelection(this)">
                        
                        <div class="row-selection-indicator">
                            <i class="fas fa-check"></i>
                        </div>
                        
                        <div class="row-item bib-col">
                            <span class="row-bib-badge"><?= htmlspecialchars($p['bib']) ?></span>
                        </div>
                        
                        <div class="row-item name-col">
                            <div class="row-name">
                                <?= htmlspecialchars($p['first_name'] . ' ' . $p['last_name']) ?>
                            </div>
                            <div class="row-id">&nbsp;ID: <?= $p['id'] ?></div>
                        </div>
                        
                        <div class="row-item club-col">
                            <span class="row-club detail-badge club"><?= htmlspecialchars($p['club'] ?? 'No Club') ?></span>
                        </div>
                        
                        <div class="row-item category-col">
                            <span class="row-category detail-badge category"><?= htmlspecialchars($p['category'] ?? 'No Category') ?></span>
                        </div>
                        
                        <div class="row-item gender-col ">
                            <span class="row-gender detail-badge gender gender-<?= $p['gender'] === 'M' ? 'male' : 'female' ?>">
                                <i class="fas fa-<?= $p['gender'] === 'M' ? 'male' : 'female' ?> me-1"></i>
                                <?= htmlspecialchars($p['gender'] ?? '') ?>
                            </span>
                        </div>
                        
                        <div class="row-item year-col">
                            <span class="row-year detail-badge year"><?= $p['date_of_birth'] ? date('Y', strtotime($p['date_of_birth'])) : '-' ?></span>
                        </div>
                        
                        <div class="row-item status-col">
                            <?php if ($p['assignment_count'] > 0): ?>
                                <span class="row-status assigned">
                                    <i class="fas fa-fire me-1"></i>
                                    Heat <?= $p['assigned_heats'] ?>
                                </span>
                            <?php else: ?>
                                <span class="row-status unassigned">
                                    <i class="fas fa-circle me-1"></i>
                                    Available
                                </span>
                            <?php endif; ?>
                        </div>
                         <div class="row-item actions-col">
                                <div class="btn-group btn-group-sm">
                                    <a href="participant_edit.php?id=<?= $p['participant_id'] ?? $p['id'] ?>" class="btn btn-outline-primary" title="Edit Participant">
                                        <i class="fas fa-edit"></i>
                                    </a>                                    
                                </div>
                            </div>
                    </div>
                <?php endforeach; ?>
            </div>
        </div>
        
        <!-- No Results Message -->
        <div id="noParticipantsMessage" class="no-participants-message" style="display: none;">
            <div class="text-center py-5">
                <i class="fas fa-search fa-3x text-muted mb-3"></i>
                <h5 class="text-muted">No participants found</h5>
                <p class="text-muted">Try adjusting your search or filter criteria</p>
                <button type="button" class="btn btn-outline-primary" onclick="clearAllFiltersAndSearch()">
                    <i class="fas fa-refresh me-1"></i>Clear All Filters
                </button>
            </div>
        </div>
    </div>
    
    <div class="participant-select-footer">
        <div class="d-flex justify-content-between align-items-center">
            <div class="form-text small">
                <span id="participantCount"><?= count($participants) ?></span> participants available • Click to select
            </div>
            <div class="selection-summary text-end">
                <small class="text-muted">
                    <span id="visibleCount"><?= count($participants) ?></span> visible • <span id="selectedCount">0</span> selected
                </small>
            </div>
        </div>
    </div>
</div>
                        </div>
                    </div>
                    <div class="row g-2 border-top pt-2 mt-2">
                        <div class="col-md-6">
                            <div class="text-muted small">
                                <strong>Tip:</strong> Use filters to narrow down participants, then select and assign them to the chosen heat.
                            </div>
                        </div>
                    <!-- Heat Selection -->
                        <div class="col-md-3">
                            <label for="heat_number" class="form-label small fw-bold">
                                <i class="fas fa-fire me-1 text-primary"></i>Heat Selection
                            </label>
                            <?php
                            // Fetch heats for selected event
                            $heat_options = [];
                            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]);
                                $heat_options = $stmt->fetchAll(PDO::FETCH_ASSOC);
                            }
                            ?>
                            <select name="heat_number" id="heat_number" class="form-select form-select-sm" required>
                                <option value="">-- Select Heat --</option>
                                <?php foreach ($heat_options as $heat): ?>
                                    <option value="<?= $heat['heat_number'] ?>">
                                        Heat <?= $heat['heat_number'] ?><?= $heat['heat_name'] ? ' – ' . htmlspecialchars($heat['heat_name']) : '' ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                            <div class="form-text small">Choose the target heat for assignment</div>
                        </div>
                    <!-- Action Buttons -->
                     <div class="col-md-3">
                        <label class="form-label small fw-bold">&nbsp;</label>
                        <div class="d-flex gap-1">
                            <button type="button" class="btn btn-outline-secondary btn-sm" onclick="clearAllFilters()">
                                <i class="fas fa-undo"></i>
                            </button>
                            <button type="button" id="ajaxAssignBtn" class="btn btn-success btn-sm">
                                <i class="fas fa-user-plus me-1"></i>Assign
                            </button>
                        </div>
                    </div>
                    
                    </div>
                </form>
            </div>
        </div>
        
        <!-- Heat Assignments Card -->
        <div class="card">
            <!-- ... rest of the heat assignments table ... -->
        </div>
<?php endif; ?>

<div class="card">
    <div class="card-header bg-light py-2 d-flex justify-content-between align-items-center">
        <h6 class="mb-0">
            <i class="fas fa-fire me-1"></i>Heat Assignments (<?= count($assignments) ?> participants)
        </h6>
        <div class="btn-group btn-group-sm">
            <button class="btn btn-outline-secondary active btn-sm">
                <i class="fas fa-table"></i>
            </button>
        </div>
    </div>
    <div class="card-body p-0">
        
        <!-- Dynamic Filters -->
        <div class="p-2 bg-light border-bottom">
            <div class="row g-1">
                <div class="col-md-2">
                    <select id="filterHeat" class="form-select form-select-sm" onchange="filterReorderTable()">
                        <option value="">All Heats</option>
                        <?php
                        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]);
                            foreach ($stmt->fetchAll(PDO::FETCH_ASSOC) as $heat) {
                                echo '<option value="' . $heat['heat_number'] . '">' . $heat['heat_number'] . ($heat['heat_name'] ? ' – ' . htmlspecialchars($heat['heat_name']) : '') . '</option>';
                            }
                        }
                        ?>
                    </select>
                </div>
                <div class="col-md-2">
                    <select id="filterCategory" class="form-select form-select-sm" onchange="filterReorderTable()">
                        <option value="">All Categories</option>
                        <option value="No Category">No Category</option>
                        <?php 
                        // Get categories from current assignments
                        $assignment_categories = array_unique(array_filter(array_column($assignments, 'category')));
                        sort($assignment_categories);
                        foreach ($assignment_categories as $c): ?>
                            <option value="<?= htmlspecialchars($c) ?>"><?= htmlspecialchars($c) ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div class="col-md-2">
                    <select id="filterClub" class="form-select form-select-sm" onchange="filterReorderTable()">
                        <option value="">All Clubs</option>
                        <?php foreach ($clubs as $c): ?>
                            <option value="<?= $c ?>"><?= $c ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div class="col-md-2">
                    <select id="filterGender" class="form-select form-select-sm" onchange="filterReorderTable()">
                        <option value="">All Genders</option>
                        <?php foreach ($genders as $g): ?>
                            <option value="<?= $g ?>"><?= $g ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div class="col-md-2">
                    <select id="filterYear" class="form-select form-select-sm" onchange="filterReorderTable()">
                        <option value="">All Years</option>
                        <optgroup label="Single Years">
                            <?php foreach ($years as $y): ?>
                                <option value="<?= $y ?>"><?= $y ?></option>
                            <?php endforeach; ?>
                        </optgroup>
                        <optgroup label="Year Ranges">
                            <option value="2010-2015">2010-2015</option>
                            <option value="2016-2020">2016-2020</option>
                            <option value="2021-2025">2021-2025</option>
                            <option value="before-2010">Before 2010</option>
                            <option value="after-2020">After 2020</option>
                        </optgroup>
                        <optgroup label="Age Groups">
                            <?php
                            $currentYear = date('Y');
                            $ageGroups = [
                                'under-18' => 'Under 18 (' . ($currentYear - 17) . '+)',
                                'under-21' => 'Under 21 (' . ($currentYear - 20) . '+)', 
                                'under-25' => 'Under 25 (' . ($currentYear - 24) . '+)',
                                'over-30' => 'Over 30 (' . ($currentYear - 30) . '-)',
                                'over-40' => 'Over 40 (' . ($currentYear - 40) . '-)',
                                'over-50' => 'Over 50 (' . ($currentYear - 50) . '-)'
                            ];
                            foreach ($ageGroups as $value => $label): ?>
                                <option value="<?= $value ?>"><?= $label ?></option>
                            <?php endforeach; ?>
                        </optgroup>
                    </select>
                </div>
                <div class="col-md-2 d-flex align-items-end">
                    <button type="button" class="btn btn-outline-secondary btn-sm w-100" onclick="clearFilters()">
                        <i class="fas fa-times me-1"></i>Clear
                    </button>
                </div>
            </div>
        </div>

              <!-- Action Buttons -->
        <div class="p-3 border-bottom bg-white">
            <div class="d-flex flex-wrap gap-1 align-items-center">
                <button type="button" id="reverseSelectedBtn" class="btn btn-outline-secondary btn-sm">
                    <i class="fas fa-exchange-alt me-1"></i>Reverse Selected
                </button>
                <button type="button" id="shuffleSelectedBtn" class="btn btn-outline-warning btn-sm">
                    <i class="fas fa-random me-1"></i>Shuffle Selected
                </button>
                <button type="button" id="sortByNameBtn" class="btn btn-outline-info btn-sm">
                    <i class="fas fa-sort-alpha-down me-1"></i>Sort by Name
                </button>
                <button type="button" id="sortBybibBtn" class="btn btn-outline-dark btn-sm">
                    <i class="fas fa-sort-numeric-down me-1"></i>Sort by bib
                </button>
                <button type="button" id="sortByYearBtn" class="btn btn-outline-secondary btn-sm">
                    <i class="fas fa-calendar me-1"></i>Sort by Year
                </button>
                <div class="vr mx-1"></div>
                <button type="button" class="btn btn-outline-success btn-sm" data-bs-toggle="modal" data-bs-target="#assignbibModal">
                    <i class="fas fa-hashtag me-1"></i>Assign bib
                </button>
                <button type="button" id="moveToHeatBtn" class="btn btn-outline-info btn-sm" data-bs-toggle="modal" data-bs-target="#moveToHeatModal">
                    <i class="fas fa-arrow-right me-1"></i>Move to Heat
                </button>
                <button type="button" id="promoteToHeatBtn" class="btn btn-outline-warning btn-sm">
                    <i class="fas fa-level-up-alt me-1"></i>Promote to Heat
                </button>
                <div class="vr mx-1"></div>
                <button type="submit" class="btn btn-outline-danger btn-sm" form="bulkDeleteForm">
                    <i class="fas fa-trash me-1"></i>Remove Selected
                </button>
            </div>
        </div>

        <!-- Table -->
        <div class="table-responsive">
            <table id="reorder-table" class="table table-hover mb-0 table-participants">
                <thead class="table-light">
                    <tr>
                        <th width="40">
                            <input type="checkbox" id="bulk-check-master" class="form-check-input">
                        </th>
                        <th width="60">#</th>
                        <th width="80">Heat</th>
                        <th width="80">bib</th>
                        <th>Name</th>                        
                        <th>Club</th>
                        <th>Category</th>
                        <th width="80">Gender</th>
                        <th width="80">Year</th>
                        <th width="120">Actions</th>
                    </tr>
                </thead>
                <tbody>
                    <?php if (empty($assignments)): ?>
                        <tr>
                            <td colspan="10" class="text-center text-muted py-4">
                                <i class="fas fa-fire fa-3x mb-3 opacity-50"></i>
                                <p class="mb-0">No participants assigned to heats yet</p>
                                <small class="text-muted">Use the assignment form above to add participants</small>
                            </td>
                        </tr>
                    <?php else: ?>
                        <?php foreach ($assignments as $a): ?>
                         <tr data-id="<?= $a['id'] ?>"
                            data-heat="<?= $a['heat_number'] ?>"
                            data-category="<?= htmlspecialchars($a['category'] ?? 'No Category') ?>"
                            data-club="<?= htmlspecialchars($a['club'] ?? '') ?>"
                            data-gender="<?= htmlspecialchars($a['gender'] ?? '') ?>"
                            data-year="<?= $a['date_of_birth'] ? date('Y', strtotime($a['date_of_birth'])) : '' ?>">
                            <td>
                                <input type="checkbox" name="delete_ids[]" value="<?= $a['id'] ?>" class="form-check-input bulk-check" form="bulkDeleteForm">
                            </td>
                            <td>
                                <span class="serial-number text-muted small"></span>
                            </td>
                            <td>
                                <span class="badge bg-primary rounded-pill heat-badge heat-number-<?= $a['heat_number'] ?>"><?= $a['heat_number'] ?></span>
                            </td>
                            <td>
                                <span class="row-bib-badge"><?= $a['bib'] ?></span>
                            </td>
                            <td>
                                <div class="row-name"><?= htmlspecialchars($a['first_name'] . ' ' . $a['last_name']) ?></div>
                                <div class="row-id"><small class="text-muted">ID: <?= $a['participant_id'] ?></small></div>
                            </td>                            
                            <td>
                                <span class="row-category detail-badge club"><?= htmlspecialchars($a['club']) ?></span>
                            </td>
                            <td>
                                <span class="row-category detail-badge category"><?= htmlspecialchars($a['category'] ?? 'No Category') ?></span>
                                
                            </td>
                            <td>
                                
                                <span class="row-gender detail-badge gender gender-<?= $a['gender'] === 'M' ? 'male' : 'female' ?>">
                                    <i class="fas fa-<?= $a['gender'] === 'M' ? 'male' : 'female' ?> me-1"></i>
                                    <?= htmlspecialchars($a['gender']) ?>
                                </span>
                            </td>
                            <td>
                                <span class="row-year detail-badge year"><?= date('Y', strtotime($a['date_of_birth'] ?? '')) ?></span>
                            </td>
                            <td>
                                <div class="btn-group btn-group-sm">
                                    <a href="participant_edit.php?id=<?= $a['participant_id'] ?? $a['id'] ?>" class="btn btn-outline-primary" title="Edit Participant">
                                        <i class="fas fa-edit"></i>
                                    </a>
                                    <a href="?delete_id=<?= $a['id'] ?>&event_id=<?= $selected_event ?>" class="btn btn-outline-danger" title="Remove from Heat" onclick="return confirm('Remove from heat?')">
                                        <i class="fas fa-times"></i>
                                    </a>
                                </div>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>

<!-- Bulk Delete Form (hidden) - Move this right after the table -->
<form id="bulkDeleteForm" method="post" action="heats_configure.php?event_id=<?= $selected_event ?>" style="display: none;">
    <input type="hidden" name="bulk_delete" value="1">
    <!-- Checkboxes are linked via form="bulkDeleteForm" attribute -->
</form>



<script>
// Debug version of filterParticipants
function filterParticipants() {
    console.log('filterParticipants called');
    
    const category = document.getElementById('categoryFilter').value;
    const gender = document.getElementById('genderFilter').value;
    const club = document.getElementById('clubFilter').value;
    const year = document.getElementById('yearFilter').value;
    const options = document.querySelectorAll('#participantSelect option');
    
    console.log('Filter values:', { category, gender, club, year });
    console.log('Options found:', options.length);
    
    let visibleCount = 0;
    
    options.forEach((option, index) => {
        let show = true;
        
        const optionData = {
            category: option.dataset.category || '',
            gender: option.dataset.gender || '',
            club: option.dataset.club || '',
            year: option.dataset.year || (option.dataset.date_of_birth ? option.dataset.date_of_birth.substring(0, 4) : ''),
            date_of_birth: option.dataset.date_of_birth || ''
        };
        
        // Debug first few options
        if (index < 3) {
            console.log(`Option ${index}:`, {
                text: option.textContent.trim(),
                value: option.value,
                data: optionData
            });
        }
        
        // Apply filters
        if (category && optionData.category !== category) show = false;
        if (gender && optionData.gender !== gender) show = false;
        if (club && optionData.club !== club) show = false;
        if (year && optionData.year !== year) show = false;
        
        // Set visibility
        option.style.display = show ? '' : 'none';
        if (show) visibleCount++;
        
        // Debug filtering result for first few options
        if (index < 3) {
            console.log(`Option ${index} show:`, show);
        }
    });
    
    console.log('Visible count:', visibleCount);
    
    // Update participant count
    const countElement = document.getElementById('participantCount');
    if (countElement) {
        countElement.textContent = visibleCount;
    }
    
    // Clear selection of hidden options
    options.forEach(option => {
        if (option.style.display === 'none') {
            option.selected = false;
        }
    });
}

// Select all visible participants
function selectAllVisible() {
    const options = document.querySelectorAll('#participantSelect option');
    let selectedCount = 0;
    
    options.forEach(option => {
        if (option.style.display !== 'none') {
            option.selected = true;
            selectedCount++;
        }
    });
    
    console.log('Selected', selectedCount, 'visible participants');
}

// Clear selection
function clearSelection() {
    const options = document.querySelectorAll('#participantSelect option');
    options.forEach(option => {
        option.selected = false;
    });
    console.log('Selection cleared');
}

// Clear all filters
function clearAllFilters() {
    document.getElementById('categoryFilter').value = '';
    document.getElementById('genderFilter').value = '';
    document.getElementById('clubFilter').value = '';
    document.getElementById('yearFilter').value = '';
    filterParticipants();
    clearSelection();
    console.log('All filters cleared');
}

// Test function to verify everything is working
function testFilters() {
    console.log('Testing filters...');
    const participantSelect = document.getElementById('participantSelect');
    const categoryFilter = document.getElementById('categoryFilter');
    
    console.log('participantSelect found:', !!participantSelect);
    console.log('categoryFilter found:', !!categoryFilter);
    
    if (participantSelect) {
        console.log('Total options in participantSelect:', participantSelect.options.length);
        
        // Test first option data
        if (participantSelect.options.length > 0) {
            const firstOption = participantSelect.options[0];
            console.log('First option data:', {
                text: firstOption.textContent,
                category: firstOption.dataset.category,
                gender: firstOption.dataset.gender,
                club: firstOption.dataset.club,
                year: firstOption.dataset.year
            });
        }
    }
    
    if (categoryFilter && categoryFilter.options.length > 1) {
        console.log('Testing category filter...');
        //categoryFilter.value = categoryFilter.options[1].value;
        filterParticipants();
    }
}

// Run test when page loads
document.addEventListener('DOMContentLoaded', function() {
    console.log('DOM loaded, running test...');
    setTimeout(testFilters, 1000);
});
</script>
<script>

function filterReorderTable() {
    const heat = document.getElementById('filterHeat').value;
    const category = document.getElementById('filterCategory').value;
    const club = document.getElementById('filterClub').value;
    const gender = document.getElementById('filterGender').value;
    const yearFilter = document.getElementById('filterYear').value;
    
    const currentYear = new Date().getFullYear();
    let serial = 1;
    
    document.querySelectorAll('#reorder-table tbody tr').forEach(row => {
        // Skip the "no data" row
        if (row.cells.length === 1) return;
        
        let show = true;
        const rowYear = parseInt(row.dataset.year);
        
        if (heat && row.dataset.heat !== heat) show = false;
        if (category && row.dataset.category !== category) show = false;
        if (club && row.dataset.club !== club) show = false;
        if (gender && row.dataset.gender !== gender) show = false;
        
        // Enhanced year filtering with ranges
        if (yearFilter && show) {
            if (yearFilter.includes('-') && !yearFilter.startsWith('before-') && !yearFilter.startsWith('after-')) {
                // Handle year ranges like "2010-2015"
                const [startYear, endYear] = yearFilter.split('-').map(y => parseInt(y));
                if (rowYear < startYear || rowYear > endYear) show = false;
            } else if (yearFilter === 'before-2010') {
                if (rowYear >= 2010) show = false;
            } else if (yearFilter === 'after-2020') {
                if (rowYear <= 2020) show = false;
            } else if (yearFilter.startsWith('under-')) {
                // Age group filters
                const ageLimit = parseInt(yearFilter.split('-')[1]);
                const birthYear = currentYear - ageLimit;
                if (rowYear <= birthYear) show = false;
            } else if (yearFilter.startsWith('over-')) {
                // Age group filters
                const ageLimit = parseInt(yearFilter.split('-')[1]);
                const birthYear = currentYear - ageLimit;
                if (rowYear >= birthYear) show = false;
            } else {
                // Single year filter
                if (row.dataset.year !== yearFilter) show = false;
            }
        }
        
        row.style.display = show ? '' : 'none';
        
        // Set serial number only for visible rows
        if (show) {
            const serialCell = row.querySelector('.serial-number');
            if (serialCell) {
                serialCell.textContent = serial++;
            }
        }
    });
    
    // Update master checkbox state
    updateMasterCheckbox();
    
    // Update visible count in header
    const visibleCount = document.querySelectorAll('#reorder-table tbody tr:not([style*="display: none"])').length;
    const headerText = document.querySelector('.card-header h6');
    if (headerText) {
        const originalText = headerText.textContent.replace(/\(\d+[^)]*\)/, '');
        headerText.innerHTML = `<i class="fas fa-fire me-2"></i>${originalText.trim()} (${visibleCount} visible)`;
    }
}

function clearFilters() {
    document.getElementById('filterHeat').value = '';
    document.getElementById('filterCategory').value = '';
    document.getElementById('filterClub').value = '';
    document.getElementById('filterGender').value = '';
    document.getElementById('filterYear').value = '';
    filterReorderTable();
}

function updateMasterCheckbox() {
    const visibleCheckboxes = document.querySelectorAll('#reorder-table tbody tr:not([style*="display: none"]) .bulk-check');
    const checkedBoxes = document.querySelectorAll('#reorder-table tbody tr:not([style*="display: none"]) .bulk-check:checked');
    const masterCheckbox = document.getElementById('bulk-check-master');
    
    if (visibleCheckboxes.length === 0) {
        masterCheckbox.indeterminate = false;
        masterCheckbox.checked = false;
    } else if (checkedBoxes.length === visibleCheckboxes.length) {
        masterCheckbox.indeterminate = false;
        masterCheckbox.checked = true;
    } else if (checkedBoxes.length > 0) {
        masterCheckbox.indeterminate = true;
        masterCheckbox.checked = false;
    } else {
        masterCheckbox.indeterminate = false;
        masterCheckbox.checked = false;
    }
}

function confirmBulkDelete() {
    const selectedCount = document.querySelectorAll('#reorder-table .bulk-check:checked').length;
    if (selectedCount === 0) {
        alert('Please select participants to remove.');
        return false;
    }
    return confirm(`Remove ${selectedCount} selected participant(s) from their heats?`);
}

// Update master checkbox functionality to work with the form
jQuery('#bulk-check-master').on('change', function () {
    const checked = this.checked;
    jQuery('#reorder-table tbody tr:visible .bulk-check').each(function () {
        this.checked = checked;
        jQuery(this).closest('tr').toggleClass('selected-row', checked);
    });
    updateMasterCheckbox();
});

// Individual checkbox functionality
jQuery(document).on('change', '.bulk-check', function () {
    jQuery(this).closest('tr').toggleClass('selected-row', this.checked);
    updateMasterCheckbox();
});

// Make sure the bulk delete button works
jQuery(document).on('click', 'button[form="bulkDeleteForm"]', function(e) {
    e.preventDefault();
    if (confirmBulkDelete()) {
        jQuery('#bulkDeleteForm').submit();
    }
});

// Initial numbering on page load
document.addEventListener('DOMContentLoaded', function() {
    let serial = 1;
    document.querySelectorAll('#reorder-table tbody tr').forEach(row => {
        const serialCell = row.querySelector('.serial-number');
        if (serialCell) {
            serialCell.textContent = serial++;
        }
    });
    
    // Update master checkbox on individual checkbox change
    document.addEventListener('change', function(e) {
        if (e.target.classList.contains('bulk-check')) {
            updateMasterCheckbox();
        }
    });
});

// Enhanced participant selection with card-based UX
let selectedParticipants = new Set();

// Initialize the interface
document.addEventListener('DOMContentLoaded', function() {
    updateParticipantCounts();
    updateSelectionStatus();
});

// Toggle participant selection
function toggleParticipantSelection(cardElement) {
    const participantId = cardElement.dataset.id;
    const hiddenOption = document.querySelector(`#participantSelect option[value="${participantId}"]`);
    
    if (selectedParticipants.has(participantId)) {
        // Deselect
        selectedParticipants.delete(participantId);
        cardElement.classList.remove('selected');
        if (hiddenOption) hiddenOption.selected = false;
    } else {
        // Select
        selectedParticipants.add(participantId);
        cardElement.classList.add('selected');
        if (hiddenOption) hiddenOption.selected = true;
    }
    
    updateSelectionStatus();
}

// Enhanced filtering with card visibility
function filterParticipants() {
    console.log('filterParticipants called');
    
    const category = document.getElementById('categoryFilter').value;
    const gender = document.getElementById('genderFilter').value;
    const club = document.getElementById('clubFilter').value;
    const year = document.getElementById('yearFilter').value;
    const cards = document.querySelectorAll('.participant-card-item');
    
    console.log('Filter values:', { category, gender, club, year });
    
    let visibleCount = 0;
    
    cards.forEach((card, index) => {
        let show = true;
        
        const cardData = {
            category: card.dataset.category || '',
            gender: card.dataset.gender || '',
            club: card.dataset.club || '',
            year: card.dataset.year || ''
        };
        
        // Apply filters
        if (category && cardData.category !== category) show = false;
        if (gender && cardData.gender !== gender) show = false;
        if (club && cardData.club !== club) show = false;
        if (year && cardData.year !== year) show = false;
        
        // Set visibility with animation
        if (show) {
            card.classList.remove('hidden');
            card.classList.add('show');
            visibleCount++;
        } else {
            card.classList.add('hidden');
            card.classList.remove('show');
            
            // Deselect if hidden
            const participantId = card.dataset.id;
            if (selectedParticipants.has(participantId)) {
                selectedParticipants.delete(participantId);
                card.classList.remove('selected');
                const hiddenOption = document.querySelector(`#participantSelect option[value="${participantId}"]`);
                if (hiddenOption) hiddenOption.selected = false;
            }
        }
    });
    
    console.log('Visible count:', visibleCount);
    updateParticipantCounts();
    updateSelectionStatus();
    showNoResultsMessage(visibleCount === 0);
}

// Search functionality
function searchParticipants() {
    const searchTerm = document.getElementById('participantSearch').value.toLowerCase();
    const cards = document.querySelectorAll('.participant-card-item');
    
    let visibleCount = 0;
    
    cards.forEach(card => {
        const searchText = card.dataset.searchText || '';
        const matchesSearch = searchTerm === '' || searchText.includes(searchTerm);
        
        // Also check if it passes current filters
        const category = document.getElementById('categoryFilter').value;
        const gender = document.getElementById('genderFilter').value;
        const club = document.getElementById('clubFilter').value;
        const year = document.getElementById('yearFilter').value;
        
        let passesFilters = true;
        if (category && card.dataset.category !== category) passesFilters = false;
        if (gender && card.dataset.gender !== gender) passesFilters = false;
        if (club && card.dataset.club !== club) passesFilters = false;
        if (year && card.dataset.year !== year) passesFilters = false;
        
        const show = matchesSearch && passesFilters;
        
        if (show) {
            card.classList.remove('hidden');
            card.classList.add('show');
            visibleCount++;
        } else {
            card.classList.add('hidden');
            card.classList.remove('show');
            
            // Deselect if hidden
            const participantId = card.dataset.id;
            if (selectedParticipants.has(participantId)) {
                selectedParticipants.delete(participantId);
                card.classList.remove('selected');
                const hiddenOption = document.querySelector(`#participantSelect option[value="${participantId}"]`);
                if (hiddenOption) hiddenOption.selected = false;
            }
        }
    });
    
    updateParticipantCounts();
    updateSelectionStatus();
    showNoResultsMessage(visibleCount === 0);
}

// Clear search
function clearSearch() {
    document.getElementById('participantSearch').value = '';
    searchParticipants();
}

// Select all visible participants
function selectAllVisible() {
    const visibleCards = document.querySelectorAll('.participant-card-item:not(.hidden)');
    let selectedCount = 0;
    
    visibleCards.forEach(card => {
        const participantId = card.dataset.id;
        if (!selectedParticipants.has(participantId)) {
            selectedParticipants.add(participantId);
            card.classList.add('selected');
            
            const hiddenOption = document.querySelector(`#participantSelect option[value="${participantId}"]`);
            if (hiddenOption) hiddenOption.selected = true;
            
            selectedCount++;
        }
    });
    
    updateSelectionStatus();
    
    // Visual feedback
    if (selectedCount > 0) {
        document.getElementById('participantStatusBadge').classList.add('has-selection');
        setTimeout(() => {
            document.getElementById('participantStatusBadge').classList.remove('has-selection');
        }, 1000);
    }
    
    console.log('Selected', selectedCount, 'visible participants');
}

// Clear selection
function clearSelection() {
    selectedParticipants.clear();
    
    // Update all cards
    document.querySelectorAll('.participant-card-item').forEach(card => {
        card.classList.remove('selected');
    });
    
    // Update hidden select
    document.querySelectorAll('#participantSelect option').forEach(option => {
        option.selected = false;
    });
    
    updateSelectionStatus();
    console.log('Selection cleared');
}

// Clear all filters and search
function clearAllFiltersAndSearch() {
    document.getElementById('categoryFilter').value = '';
    document.getElementById('genderFilter').value = '';
    document.getElementById('clubFilter').value = '';
    document.getElementById('yearFilter').value = '';
    document.getElementById('participantSearch').value = '';
    
    filterParticipants();
    clearSelection();
    console.log('All filters and search cleared');
}

// Alias for backward compatibility
function clearAllFilters() {
    clearAllFiltersAndSearch();
}

// Update participant counts
function updateParticipantCounts() {
    const allCards = document.querySelectorAll('.participant-card-item');
    const visibleCards = document.querySelectorAll('.participant-card-item:not(.hidden)');
    
    document.getElementById('participantCount').textContent = allCards.length;
    document.getElementById('visibleCount').textContent = visibleCards.length;
}

// Update selection status
function updateSelectionStatus() {
    const selectedCount = selectedParticipants.size;
    
    document.getElementById('selectedCount').textContent = selectedCount;
    
    const badge = document.getElementById('participantStatusBadge');
    if (selectedCount > 0) {
        badge.textContent = `${selectedCount} selected`;
        badge.className = 'badge bg-success ms-2';
    } else {
        badge.textContent = '0 selected';
        badge.className = 'badge bg-info ms-2';
    }
}

// Show/hide no results message
function showNoResultsMessage(show) {
    const noResultsMessage = document.getElementById('noParticipantsMessage');
    const participantGrid = document.getElementById('participantGrid');
    
    if (show) {
        noResultsMessage.style.display = 'block';
        participantGrid.style.display = 'none';
    } else {
        noResultsMessage.style.display = 'none';
        participantGrid.style.display = 'grid';
    }
}

// Enhanced keyboard shortcuts
document.addEventListener('keydown', function(e) {
    // Ctrl/Cmd + A to select all visible
    if ((e.ctrlKey || e.metaKey) && e.key === 'a' && document.activeElement.id !== 'participantSearch') {
        e.preventDefault();
        selectAllVisible();
    }
    
    // Escape to clear selection
    if (e.key === 'Escape') {
        clearSelection();
        if (document.activeElement.id === 'participantSearch') {
            document.activeElement.blur();
        }
    }
    
    // Ctrl/Cmd + F to focus search
    if ((e.ctrlKey || e.metaKey) && e.key === 'f') {
        e.preventDefault();
        document.getElementById('participantSearch').focus();
    }
});

// Touch support for mobile
document.addEventListener('touchstart', function() {
    // Enable touch selection
    document.querySelectorAll('.participant-card-item').forEach(card => {
        card.addEventListener('touchend', function(e) {
            e.preventDefault();
            toggleParticipantSelection(this);
        });
    });
});
// View Management Functions
let currentView = 'grid'; // 'grid' or 'row'

function switchToGridView() {
    if (currentView === 'grid') return;
    
    currentView = 'grid';
    
    // Update button states
    document.getElementById('gridViewBtn').classList.add('active');
    document.getElementById('rowViewBtn').classList.remove('active');
    
    // Show/hide views
    document.getElementById('participantGridView').style.display = 'block';
    document.getElementById('participantRowView').style.display = 'none';
    
    // Update selection to match current state
    syncSelectionBetweenViews();
    
    console.log('Switched to grid view');
}

function switchToRowView() {
    if (currentView === 'row') return;
    
    currentView = 'row';
    
    // Update button states
    document.getElementById('rowViewBtn').classList.add('active');
    document.getElementById('gridViewBtn').classList.remove('active');
    
    // Show/hide views
    document.getElementById('participantGridView').style.display = 'none';
    document.getElementById('participantRowView').style.display = 'block';
    
    // Update selection to match current state
    syncSelectionBetweenViews();
    
    console.log('Switched to row view');
}

function syncSelectionBetweenViews() {
    // Sync selection state between grid and row views
    selectedParticipants.forEach(participantId => {
        const gridCard = document.querySelector(`.participant-card-item[data-id="${participantId}"]`);
        const rowItem = document.querySelector(`.participant-row-item[data-id="${participantId}"]`);
        
        if (gridCard) gridCard.classList.add('selected');
        if (rowItem) rowItem.classList.add('selected');
    });
}

// Enhanced participant selection that works with both views
function toggleParticipantSelection(element) {
    const participantId = element.dataset.id;
    const hiddenOption = document.querySelector(`#participantSelect option[value="${participantId}"]`);
    
    // Find corresponding elements in both views
    const gridCard = document.querySelector(`.participant-card-item[data-id="${participantId}"]`);
    const rowItem = document.querySelector(`.participant-row-item[data-id="${participantId}"]`);
    
    if (selectedParticipants.has(participantId)) {
        // Deselect
        selectedParticipants.delete(participantId);
        if (gridCard) gridCard.classList.remove('selected');
        if (rowItem) rowItem.classList.remove('selected');
        if (hiddenOption) hiddenOption.selected = false;
    } else {
        // Select
        selectedParticipants.add(participantId);
        if (gridCard) gridCard.classList.add('selected');
        if (rowItem) rowItem.classList.add('selected');
        if (hiddenOption) hiddenOption.selected = true;
    }
    
    updateSelectionStatus();
}

// Enhanced filtering that works with both views
function filterParticipants() {
    console.log('filterParticipants called - current view:', currentView);
    
    const category = document.getElementById('categoryFilter').value;
    const gender = document.getElementById('genderFilter').value;
    const club = document.getElementById('clubFilter').value;
    const year = document.getElementById('yearFilter').value;
    
    console.log('Filter values:', { category, gender, club, year });
    
    let visibleCount = 0;
    
    if (currentView === 'grid') {
        const cards = document.querySelectorAll('.participant-card-item');
        
        cards.forEach((card) => {
            let show = true;
            
            const cardData = {
                category: card.dataset.category || '',
                gender: card.dataset.gender || '',
                club: card.dataset.club || '',
                year: card.dataset.year || ''
            };
            
            // Apply filters
            if (category && cardData.category !== category) show = false;
            if (gender && cardData.gender !== gender) show = false;
            if (club && cardData.club !== club) show = false;
            if (year && cardData.year !== year) show = false;
            
            // Set visibility with animation
            if (show) {
                card.classList.remove('hidden');
                card.classList.add('show');
                visibleCount++;
            } else {
                card.classList.add('hidden');
                card.classList.remove('show');
                
                // Deselect if hidden
                const participantId = card.dataset.id;
                if (selectedParticipants.has(participantId)) {
                    selectedParticipants.delete(participantId);
                    card.classList.remove('selected');
                    const hiddenOption = document.querySelector(`#participantSelect option[value="${participantId}"]`);
                    if (hiddenOption) hiddenOption.selected = false;
                    
                    // Also update row view
                    const rowItem = document.querySelector(`.participant-row-item[data-id="${participantId}"]`);
                    if (rowItem) rowItem.classList.remove('selected');
                }
            }
        });
    } else {
        const rows = document.querySelectorAll('.participant-row-item');
        
        rows.forEach((row) => {
            let show = true;
            
            const rowData = {
                category: row.dataset.category || '',
                gender: row.dataset.gender || '',
                club: row.dataset.club || '',
                year: row.dataset.year || ''
            };
            
            // Apply filters
            if (category && rowData.category !== category) show = false;
            if (gender && rowData.gender !== gender) show = false;
            if (club && rowData.club !== club) show = false;
            if (year && rowData.year !== year) show = false;
            
            // Set visibility with animation
            if (show) {
                row.classList.remove('hidden');
                row.classList.add('show');
                visibleCount++;
            } else {
                row.classList.add('hidden');
                row.classList.remove('show');
                
                // Deselect if hidden
                const participantId = row.dataset.id;
                if (selectedParticipants.has(participantId)) {
                    selectedParticipants.delete(participantId);
                    row.classList.remove('selected');
                    const hiddenOption = document.querySelector(`#participantSelect option[value="${participantId}"]`);
                    if (hiddenOption) hiddenOption.selected = false;
                    
                    // Also update grid view
                    const gridCard = document.querySelector(`.participant-card-item[data-id="${participantId}"]`);
                    if (gridCard) gridCard.classList.remove('selected');
                }
            }
        });
    }
    
    console.log('Visible count:', visibleCount);
    updateParticipantCounts();
    updateSelectionStatus();
    showNoResultsMessage(visibleCount === 0);
}

// Enhanced search that works with both views
function searchParticipants() {
    const searchTerm = document.getElementById('participantSearch').value.toLowerCase();
    
    let visibleCount = 0;
    
    if (currentView === 'grid') {
        const cards = document.querySelectorAll('.participant-card-item');
        
        cards.forEach(card => {
            const searchText = card.dataset.searchText || '';
            const matchesSearch = searchTerm === '' || searchText.includes(searchTerm);
            
            // Also check if it passes current filters
            const passesFilters = checkElementPassesFilters(card);
            const show = matchesSearch && passesFilters;
            
            if (show) {
                card.classList.remove('hidden');
                card.classList.add('show');
                visibleCount++;
            } else {
                card.classList.add('hidden');
                card.classList.remove('show');
                
                // Deselect if hidden
                deselectParticipant(card.dataset.id);
            }
        });
    } else {
        const rows = document.querySelectorAll('.participant-row-item');
        
        rows.forEach(row => {
            const searchText = row.dataset.searchText || '';
            const matchesSearch = searchTerm === '' || searchText.includes(searchTerm);
            
            // Also check if it passes current filters
            const passesFilters = checkElementPassesFilters(row);
            const show = matchesSearch && passesFilters;
            
            if (show) {
                row.classList.remove('hidden');
                row.classList.add('show');
                visibleCount++;
            } else {
                row.classList.add('hidden');
                row.classList.remove('show');
                
                // Deselect if hidden
                deselectParticipant(row.dataset.id);
            }
        });
    }
    
    updateParticipantCounts();
    updateSelectionStatus();
    showNoResultsMessage(visibleCount === 0);
}

function checkElementPassesFilters(element) {
    const category = document.getElementById('categoryFilter').value;
    const gender = document.getElementById('genderFilter').value;
    const club = document.getElementById('clubFilter').value;
    const year = document.getElementById('yearFilter').value;
    
    let passesFilters = true;
    if (category && element.dataset.category !== category) passesFilters = false;
    if (gender && element.dataset.gender !== gender) passesFilters = false;
    if (club && element.dataset.club !== club) passesFilters = false;
    if (year && element.dataset.year !== year) passesFilters = false;
    
    return passesFilters;
}

function deselectParticipant(participantId) {
    if (selectedParticipants.has(participantId)) {
        selectedParticipants.delete(participantId);
        
        const gridCard = document.querySelector(`.participant-card-item[data-id="${participantId}"]`);
        const rowItem = document.querySelector(`.participant-row-item[data-id="${participantId}"]`);
        const hiddenOption = document.querySelector(`#participantSelect option[value="${participantId}"]`);
        
        if (gridCard) gridCard.classList.remove('selected');
        if (rowItem) rowItem.classList.remove('selected');
        if (hiddenOption) hiddenOption.selected = false;
    }
}

// Enhanced select all visible that works with both views
function selectAllVisible() {
    const selector = currentView === 'grid' ? '.participant-card-item:not(.hidden)' : '.participant-row-item:not(.hidden)';
    const visibleElements = document.querySelectorAll(selector);
    let selectedCount = 0;
    
    visibleElements.forEach(element => {
        const participantId = element.dataset.id;
        if (!selectedParticipants.has(participantId)) {
            selectedParticipants.add(participantId);
            element.classList.add('selected');
            
            // Update corresponding element in other view
            const otherSelector = currentView === 'grid' ? 
                `.participant-row-item[data-id="${participantId}"]` : 
                `.participant-card-item[data-id="${participantId}"]`;
            const otherElement = document.querySelector(otherSelector);
            if (otherElement) otherElement.classList.add('selected');
            
            const hiddenOption = document.querySelector(`#participantSelect option[value="${participantId}"]`);
            if (hiddenOption) hiddenOption.selected = true;
            
            selectedCount++;
        }
    });
    
    updateSelectionStatus();
    
    // Visual feedback
    if (selectedCount > 0) {
        document.getElementById('participantStatusBadge').classList.add('has-selection');
        setTimeout(() => {
            document.getElementById('participantStatusBadge').classList.remove('has-selection');
        }, 1000);
    }
    
    console.log('Selected', selectedCount, 'visible participants in', currentView, 'view');
}

// Enhanced clear selection that works with both views
function clearSelection() {
    selectedParticipants.clear();
    
    // Update all elements in both views
    document.querySelectorAll('.participant-card-item, .participant-row-item').forEach(element => {
        element.classList.remove('selected');
    });
    
    // Update hidden select
    document.querySelectorAll('#participantSelect option').forEach(option => {
        option.selected = false;
    });
    
    updateSelectionStatus();
    console.log('Selection cleared for both views');
}

// Enhanced update counts that works with both views
function updateParticipantCounts() {
    const allElements = document.querySelectorAll(currentView === 'grid' ? '.participant-card-item' : '.participant-row-item');
    const visibleElements = document.querySelectorAll(currentView === 'grid' ? '.participant-card-item:not(.hidden)' : '.participant-row-item:not(.hidden)');
    
    document.getElementById('participantCount').textContent = allElements.length;
    document.getElementById('visibleCount').textContent = visibleElements.length;
}

// Enhanced show/hide no results message
function showNoResultsMessage(show) {
    const noResultsMessage = document.getElementById('noParticipantsMessage');
    const gridView = document.getElementById('participantGridView');
    const rowView = document.getElementById('participantRowView');
    
    if (show) {
        noResultsMessage.style.display = 'block';
        gridView.style.display = 'none';
        rowView.style.display = 'none';
    } else {
        noResultsMessage.style.display = 'none';
        if (currentView === 'grid') {
            gridView.style.display = 'block';
            rowView.style.display = 'none';
        } else {
            gridView.style.display = 'none';
            rowView.style.display = 'block';
        }
    }
}

// Save view preference to localStorage
function saveViewPreference(view) {
    localStorage.setItem('participantViewPreference', view);
}

function loadViewPreference() {
    const saved = localStorage.getItem('participantViewPreference');
    if (saved === 'row') {
        switchToRowView();
    }
    // Default is grid view, so no need to switch if saved is 'grid' or null
}

// Enhanced keyboard shortcuts that work with both views
document.addEventListener('keydown', function(e) {
    // Ctrl/Cmd + A to select all visible
    if ((e.ctrlKey || e.metaKey) && e.key === 'a' && document.activeElement.id !== 'participantSearch') {
        e.preventDefault();
        selectAllVisible();
    }
    
    // Escape to clear selection
    if (e.key === 'Escape') {
        clearSelection();
        if (document.activeElement.id === 'participantSearch') {
            document.activeElement.blur();
        }
    }
    
    // Ctrl/Cmd + F to focus search
    if ((e.ctrlKey || e.metaKey) && e.key === 'f') {
        e.preventDefault();
        document.getElementById('participantSearch').focus();
    }
    
    // V to toggle view (Grid/Row)
    if (e.key === 'v' || e.key === 'V') {
        if (document.activeElement.id !== 'participantSearch') {
            e.preventDefault();
            if (currentView === 'grid') {
                switchToRowView();
                saveViewPreference('row');
            } else {
                switchToGridView();
                saveViewPreference('grid');
            }
        }
    }
});

// Initialize view preference on page load
document.addEventListener('DOMContentLoaded', function() {
    loadViewPreference();
    
    // Make sure view buttons have click handlers
    document.getElementById('gridViewBtn').addEventListener('click', function() {
        switchToGridView();
        saveViewPreference('grid');
    });
    
    document.getElementById('rowViewBtn').addEventListener('click', function() {
        switchToRowView();
        saveViewPreference('row');
    });
});

// Touch support for mobile - works with both views
document.addEventListener('touchstart', function() {
    // Enable touch selection for both views
    document.querySelectorAll('.participant-card-item, .participant-row-item').forEach(element => {
        element.addEventListener('touchend', function(e) {
            e.preventDefault();
            toggleParticipantSelection(this);
        });
    });
});
// Test function for debugging
function testFilters() {
    console.log('Testing new card-based filters...');
    const participantGrid = document.getElementById('participantGrid');
    const categoryFilter = document.getElementById('categoryFilter');
    
    console.log('participantGrid found:', !!participantGrid);
    console.log('categoryFilter found:', !!categoryFilter);
    
    if (participantGrid) {
        const cards = participantGrid.querySelectorAll('.participant-card-item');
        console.log('Total cards in grid:', cards.length);
        
        if (cards.length > 0) {
            const firstCard = cards[0];
            console.log('First card data:', {
                id: firstCard.dataset.id,
                category: firstCard.dataset.category,
                gender: firstCard.dataset.gender,
                club: firstCard.dataset.club,
                year: firstCard.dataset.year
            });
        }
    }
    
    console.log('Current selection:', Array.from(selectedParticipants));
}

// Run test when page loads (for debugging)
document.addEventListener('DOMContentLoaded', function() {
    console.log('DOM loaded, running card-based test...');
    setTimeout(testFilters, 1000);
});
</script>
        

        
        
    <?php endif; ?>
</div>
<style>
tr.selected-row td {
    background-color: #d9f2ff;
}
.shuffled {
    animation: flash 0.5s ease-in-out;
}
@keyframes flash {
    0% { background-color: #fff176; }
    100% { background-color: transparent; }
}
</style>
<style>
/* Custom styling to match participant management */
.table-hover tbody tr:hover {
    background-color: rgba(0, 123, 255, 0.05);
}

tr.selected-row {
    background-color: rgba(0, 123, 255, 0.1) !important;
}

.shuffled {
    animation: flash 0.5s ease-in-out;
}

@keyframes flash {
    0% { background-color: #fff176; }
    100% { background-color: transparent; }
}

/* Sortable cursor */
#reorder-table tbody tr {
    cursor: move;
}

#reorder-table tbody tr:hover {
    background-color: rgba(0, 123, 255, 0.05);
}

/* Badge styling for pink gender */
.bg-pink {
    background-color: #f8d7da !important;
}

/* Drag helper styling */
.ui-sortable-helper {
    background-color: rgba(0, 123, 255, 0.1);
    border: 2px dashed #007bff;
}

/* Filter section styling */
.vr {
    width: 1px;
    height: 24px;
    background-color: #dee2e6;
}
.participant-select-container {
    position: relative;
    border-radius: 12px;
    overflow: hidden;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
    border: 2px solid #e9ecef;
    transition: border-color 0.3s ease;
}

.participant-select-container:focus-within {
    border-color: #0d6efd;
    box-shadow: 0 4px 12px rgba(13, 110, 253, 0.2);
}

.participant-multiselect {
    border: none !important;
    border-radius: 0 !important;
    box-shadow: none !important;
    font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
    background: linear-gradient(135deg, #ffffff 0%, #f8f9fa 100%);
    padding: 0;
}

.participant-multiselect:focus {
    outline: none;
    box-shadow: none !important;
}

.participant-option {
    padding: 0 !important;
    border: none !important;
    margin: 0 !important;
    background: transparent !important;
    border-bottom: 1px solid #f0f0f0 !important;
    transition: all 0.2s ease;
    cursor: pointer;
}

.participant-option:hover {
    background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%) !important;
    transform: translateX(4px);
}

.participant-option:checked {
    background: linear-gradient(135deg, #0d6efd 0%, #0b5ed7 100%) !important;
    color: white !important;
    transform: translateX(8px);
    box-shadow: inset 4px 0 0 rgba(255, 255, 255, 0.3);
}

.participant-option.already-assigned {
    background: linear-gradient(135deg, #e3f2fd 0%, #bbdefb 100%) !important;
    border-left: 4px solid #2196f3 !important;
}

.participant-option.already-assigned:checked {
    background: linear-gradient(135deg, #1976d2 0%, #1565c0 100%) !important;
}

.participant-card {
    padding: 12px 16px;
    display: flex;
    flex-direction: column;
    gap: 6px;
}

.participant-header {
    display: flex;
    align-items: center;
    gap: 10px;
    flex-wrap: wrap;
}

.participant-bib {
    display: inline-flex;
    align-items: center;
    justify-content: center;
    background: linear-gradient(135deg, #6c757d 0%, #495057 100%);
    color: white;
    padding: 4px 10px;
    border-radius: 20px;
    font-size: 0.75rem;
    font-weight: bold;
    min-width: 45px;
    height: 24px;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
}

.participant-option:checked .participant-bib {
    background: linear-gradient(135deg, #ffffff 0%, #e9ecef 100%);
    color: #0d6efd;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.3);
}

.participant-name {
    font-weight: 600;
    font-size: 0.9rem;
    color: #212529;
    flex-grow: 1;
}

.participant-option:checked .participant-name {
    color: white;
    font-weight: 700;
}

.assignment-badge {
    background: linear-gradient(135deg, #28a745 0%, #20c997 100%);
    color: white;
    padding: 2px 8px;
    border-radius: 12px;
    font-size: 0.7rem;
    font-weight: bold;
    display: inline-flex;
    align-items: center;
    box-shadow: 0 1px 3px rgba(0, 0, 0, 0.2);
}

.participant-option:checked .assignment-badge {
    background: linear-gradient(135deg, #ffffff 0%, #f8f9fa 100%);
    color: #28a745;
}

.participant-details {
    display: flex;
    flex-wrap: wrap;
    gap: 8px;
    align-items: center;
}

.detail-item {
    display: inline-flex;
    align-items: center;
    font-size: 0.75rem;
    padding: 2px 6px;
    border-radius: 8px;
    background: rgba(108, 117, 125, 0.1);
    color: #6c757d;
    transition: all 0.2s ease;
}

.participant-option:checked .detail-item {
    background: rgba(255, 255, 255, 0.2);
    color: rgba(255, 255, 255, 0.9);
}

.detail-item.club {
    background: rgba(13, 110, 253, 0.1);
    color: #0d6efd;
}

.detail-item.category {
    background: rgba(255, 193, 7, 0.1);
    color: #ffc107;
}

.detail-item.gender {
    background: rgba(220, 53, 69, 0.1);
    color: #dc3545;
}

.detail-item.year {
    background: rgba(108, 117, 125, 0.1);
    color: #6c757d;
}

.participant-select-footer {
    background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);
    padding: 12px 16px;
    border-top: 1px solid #dee2e6;
}

#participantStatusBadge {
    transition: all 0.3s ease;
}

#participantStatusBadge.has-selection {
    background: linear-gradient(135deg, #28a745 0%, #20c997 100%) !important;
    animation: pulse 1s ease-in-out;
}


.heat-number-1  { background-color: hsl(209, 100%, 50%) !important; } /* +14° */
.heat-number-6  { background-color: hsl(222, 100%, 50%) !important; } /* +13° */
.heat-number-2  { background-color: hsl(234, 100%, 50%) !important; } /* +12° */
.heat-number-5  { background-color: hsl(245, 100%, 50%) !important; } /* +11° */
.heat-number-4  { background-color: hsl(255, 100%, 50%) !important; } /* +10° */
.heat-number-3  { background-color: hsl(264, 100%, 50%) !important; } /* +9°  */
.heat-number-8  { background-color: hsl(272, 100%, 50%) !important; } /* +8°  */
.heat-number-7  { background-color: hsl(279, 100%, 50%) !important; } /* +7°  */
.heat-number-9  { background-color: hsl(285, 100%, 50%) !important; } /* +6°  */
.heat-number-11 { background-color: hsl(290, 100%, 50%) !important; } /* +5°  */
.heat-number-10 { background-color: hsl(294, 100%, 50%) !important; } /* +4°  */
.heat-number-13 { background-color: hsl(297, 100%, 50%) !important; } /* +3°  */
.heat-number-14 { background-color: hsl(299, 100%, 50%) !important; } /* +2° */
@keyframes pulse {
    0% { transform: scale(1); }
    50% { transform: scale(1.1); }
    100% { transform: scale(1); }
}

/* Responsive adjustments */
@media (max-width: 768px) {
    .participant-card {
        padding: 10px 12px;
    }
    
    .participant-header {
        gap: 8px;
    }
    
    .participant-bib {
        font-size: 0.7rem;
        padding: 3px 8px;
        min-width: 40px;
        height: 22px;
    }
    
    .participant-name {
        font-size: 0.85rem;
    }
    
    .detail-item {
        font-size: 0.7rem;
        padding: 1px 4px;
    }
}

/* Scrollbar styling for webkit browsers */
.participant-multiselect::-webkit-scrollbar {
    width: 8px;
}

.participant-multiselect::-webkit-scrollbar-track {
    background: #f1f1f1;
    border-radius: 4px;
}

.participant-multiselect::-webkit-scrollbar-thumb {
    background: linear-gradient(135deg, #6c757d 0%, #495057 100%);
    border-radius: 4px;
}

.participant-multiselect::-webkit-scrollbar-thumb:hover {
    background: linear-gradient(135deg, #495057 0%, #343a40 100%);
}
/* Form enhancements */
.card-header p {
    margin-top: 4px;
}

/* Button hover effects */
#ajaxAssignBtn {
    box-shadow: 0 2px 4px rgba(0,0,0,0.1);
    transition: all 0.2s ease;
}

#ajaxAssignBtn:hover {
    transform: translateY(-1px);
    box-shadow: 0 4px 8px rgba(0,0,0,0.15);
}

/* Loading state */
#ajaxAssignBtn.loading {
    position: relative;
    color: transparent;
}

#ajaxAssignBtn.loading::after {
    content: '';
    position: absolute;
    width: 16px;
    height: 16px;
    top: 50%;
    left: 50%;
    margin-left: -8px;
    margin-top: -8px;
    border: 2px solid #ffffff;
    border-radius: 50%;
    border-top-color: transparent;
    animation: spin 0.8s linear infinite;
}

@keyframes spin {
    to {
        transform: rotate(360deg);
    }
}

/* Filter section styling */
.form-select-sm {
    font-size: 0.875rem;
}

/* Responsive adjustments */
@media (max-width: 768px) {
    .participant-multiselect {
        font-size: 0.875rem;
    }
    
    .participant-bib {
        font-size: 0.7rem;
        padding: 1px 6px;
        min-width: 35px;
    }
}
/* Row View Styling */
.participant-row-container {
    border-radius: 12px;
    overflow: hidden;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
    border: 2px solid #e9ecef;
    background: #ffffff;
    max-height: 600px;
    overflow-y: auto;
}

.participant-row-header {
    display: grid;
    grid-template-columns: 80px 1fr 1fr 1fr 80px 80px 120px 80px;
    gap: 1px;
    background: #f8f9fa;
    border-bottom: 2px solid #dee2e6;
    position: sticky;
    top: 0;
    z-index: 10;
}

.row-header-item {
    padding: 12px 8px;
    font-weight: 600;
    font-size: 0.875rem;
    background: #e9ecef;
    text-align: center;
    color: #495057;
    border-right: 1px solid #dee2e6;
}

.row-header-item:last-child {
    border-right: none;
}

.participant-rows {
    background: #ffffff;
}

.participant-row-item {
    display: grid;
    grid-template-columns: 80px 1fr 1fr 1fr 80px 80px 120px 80px;
    gap: 1px;
    background: #f8f9fa;
    border-bottom: 1px solid #e9ecef;
    cursor: pointer;
    transition: all 0.2s ease;
    position: relative;
    min-height: 60px;
    align-items: center;
}

.participant-row-item:hover {
    background: #e3f2fd;
    transform: translateX(2px);
    box-shadow: 0 2px 8px rgba(0, 123, 255, 0.15);
}

.participant-row-item.selected {
    background: linear-gradient(135deg, #007bff 0%, #0056b3 100%);
    color: white;
    transform: translateX(4px);
    box-shadow: 0 4px 12px rgba(0, 123, 255, 0.3);
}

.participant-row-item.already-assigned {
    border-left: 4px solid #28a745;
    background: linear-gradient(135deg, #f8fffa 0%, #e8f5e8 100%);
}

.participant-row-item.already-assigned.selected {
    background: linear-gradient(135deg, #28a745 0%, #1e7e34 100%);
}

.row-selection-indicator {
    position: absolute;
    top: 8px;
    right: 8px;
    background: #28a745;
    color: white;
    width: 20px;
    height: 20px;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 0.7rem;
    opacity: 0;
    transform: scale(0);
    transition: all 0.3s ease;
    border: 1px solid white;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
    z-index: 5;
}

.participant-row-item.selected .row-selection-indicator {
    opacity: 1;
    transform: scale(1);
}

.row-item {
    padding: 8px;
    background: white;
    display: flex;
    align-items: center;
    justify-content: center;
    text-align: center;
    border-right: 1px solid #e9ecef;
    min-height: 44px;
}
td.row-item{    text-align: left !important;
    justify-content: flex-start !important;}
.row-item:last-child {
    border-right: none;
}

.participant-row-item.selected .row-item {
    background: rgba(255, 255, 255, 0.1);
    color: white;
}

/* Individual row item styling */
.row-bib-badge {
    background: linear-gradient(135deg, #6c757d 0%, #495057 100%);
    color: white;
    padding: 4px 8px;
    border-radius: 12px;
    font-size: 0.8rem;
    font-weight: bold;
    display: inline-flex;
    align-items: center;
    justify-content: center;
    min-width: 40px;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
}
.heat-badge {
    
    color: white;
    padding: 4px 8px;
    border-radius: 12px;
    font-size: 0.8rem;
    font-weight: bold;
    display: inline-flex;
    align-items: center;
    justify-content: center;
    
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
}
.participant-row-item.selected .row-bib-badge {
    background: linear-gradient(135deg, #ffffff 0%, #f8f9fa 100%);
    color: #007bff;
}

.name-col {
    text-align: left !important;
    justify-content: flex-start !important;
}

.row-name {
    font-weight: 600;
    font-size: 0.9rem;
    line-height: 1.2;
}
.row-name {
    display: inline-block;
}

.row-id {
    display: inline;
}
.row-id {
    font-size: 0.7rem;
    color: #6c757d;
    margin-top: 2px;
}

.participant-row-item.selected .row-id {
    color: rgba(255, 255, 255, 0.8);
}

.club-col, .category-col {
    text-align: left !important;
    justify-content: flex-start !important;
}

.row-club, .row-category {
    font-size: 0.85rem;
    padding: 2px 6px;
    border-radius: 6px;
    background: rgba(108, 117, 125, 0.1);
    display: inline-block;
    max-width: 100%;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
}

.participant-row-item.selected .row-club,
.participant-row-item.selected .row-category {
    background: rgba(255, 255, 255, 0.2);
}

.row-gender {
    font-size: 0.85rem;
    display: flex;
    align-items: center;
    gap: 4px;
}

.row-year {
    font-size: 0.85rem;
    color: #6c757d;
}

.participant-row-item.selected .row-year {
    color: rgba(255, 255, 255, 0.9);
}

.row-status {
    font-size: 0.8rem;
    padding: 4px 8px;
    border-radius: 12px;
    display: inline-flex;
    align-items: center;
    gap: 4px;
    font-weight: 500;
}

.row-status.assigned {
    background: linear-gradient(135deg, #28a745 0%, #20c997 100%);
    color: white;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
}

.row-status.unassigned {
    background: rgba(108, 117, 125, 0.1);
    color: #6c757d;
}

.participant-row-item.selected .row-status.assigned {
    background: linear-gradient(135deg, #ffffff 0%, #f8f9fa 100%);
    color: #28a745;
}

.participant-row-item.selected .row-status.unassigned {
    background: rgba(255, 255, 255, 0.2);
    color: rgba(255, 255, 255, 0.9);
}

/* View Toggle Button Styling */
.btn-group .btn.active {
    background-color: #007bff;
    border-color: #007bff;
    color: white;
}

/* Responsive adjustments for row view */
@media (max-width: 768px) {
    .participant-row-header,
    .participant-row-item {
        grid-template-columns: 60px 1fr 100px 80px 60px 60px 100px;
        font-size: 0.8rem;
    }
    
    .row-header-item,
    .row-item {
        padding: 6px 4px;
        min-height: 40px;
    }
    
    .row-name {
        font-size: 0.8rem;
    }
    
    .row-id {
        font-size: 0.65rem;
    }
    
    .row-bib-badge {
        font-size: 0.7rem;
        padding: 2px 6px;
        min-width: 35px;
    }
}

@media (max-width: 576px) {
    .participant-row-header,
    .participant-row-item {
        grid-template-columns: 50px 1fr 80px 60px 50px 50px 80px;
    }
    
    .row-header-item,
    .row-item {
        padding: 4px 2px;
        font-size: 0.75rem;
    }
    
    .row-club, .row-category {
        font-size: 0.7rem;
    }
}

/* Hide/show animation for row view */
.participant-row-item.hidden {
    display: none;
}

.participant-row-item.show {
    animation: fadeInRow 0.3s ease;
}

@keyframes fadeInRow {
    from {
        opacity: 0;
        transform: translateX(-10px);
    }
    to {
        opacity: 1;
        transform: translateX(0);
    }
}

/* Scrollbar styling for row view */
.participant-row-container::-webkit-scrollbar {
    width: 8px;
}

.participant-row-container::-webkit-scrollbar-track {
    background: #f1f1f1;
    border-radius: 4px;
}

.participant-row-container::-webkit-scrollbar-thumb {
    background: linear-gradient(135deg, #6c757d 0%, #495057 100%);
    border-radius: 4px;
}

.participant-row-container::-webkit-scrollbar-thumb:hover {
    background: linear-gradient(135deg, #495057 0%, #343a40 100%);
}

/* Ensure both views share the same container styling */
.participant-display-container {
    position: relative;
}
/* Modern Participant Grid Styling */
.participant-grid-container {
    position: relative;
    border-radius: 12px;
    overflow: hidden;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
    border: 2px solid #e9ecef;
    background: #f8f9fa;
    max-height: 600px;
    overflow-y: auto;
}

.participant-grid {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
    gap: 12px;
    padding: 16px;
}

.participant-card-item {
    background: white;
    border-radius: 12px;
    padding: 16px;
    border: 2px solid #e9ecef;
    cursor: pointer;
    transition: all 0.3s ease;
    position: relative;
    overflow: hidden;
}

.participant-card-item:hover {
    transform: translateY(-2px);
    box-shadow: 0 8px 25px rgba(0, 123, 255, 0.15);
    border-color: #007bff;
}

.participant-card-item.selected {
    background: linear-gradient(135deg, #007bff 0%, #0056b3 100%);
    color: white;
    border-color: #0056b3;
    transform: translateY(-2px);
    box-shadow: 0 8px 25px rgba(0, 123, 255, 0.3);
}

.participant-card-item.already-assigned {
    border-left: 4px solid #28a745;
    background: linear-gradient(135deg, #f8fffa 0%, #e8f5e8 100%);
}

.participant-card-item.already-assigned.selected {
    background: linear-gradient(135deg, #28a745 0%, #1e7e34 100%);
}

.participant-card-header {
    display: flex;
    justify-content: space-between;
    align-items: flex-start;
    margin-bottom: 12px;
    position: relative;
}

.participant-bib-badge {
    background: linear-gradient(135deg, #6c757d 0%, #495057 100%);
    color: white;
    padding: 6px 12px;
    border-radius: 20px;
    font-size: 0.8rem;
    font-weight: bold;
    display: inline-flex;
    align-items: center;
    justify-content: center;
    min-width: 50px;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
}

.participant-card-item.selected .participant-bib-badge {
    background: linear-gradient(135deg, #ffffff 0%, #f8f9fa 100%);
    color: #007bff;
}

.participant-selection-indicator {
    position: absolute;
    top: -8px;
    right: -8px;
    background: #28a745;
    color: white;
    width: 24px;
    height: 24px;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 0.7rem;
    opacity: 0;
    transform: scale(0);
    transition: all 0.3s ease;
    border: 2px solid white;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.2);
}

.participant-card-item.selected .participant-selection-indicator {
    opacity: 1;
    transform: scale(1);
}

.assignment-indicator {
    background: linear-gradient(135deg, #28a745 0%, #20c997 100%);
    color: white;
    padding: 2px 8px;
    border-radius: 12px;
    font-size: 0.7rem;
    font-weight: bold;
    display: flex;
    align-items: center;
    gap: 4px;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
}

.participant-card-item.selected .assignment-indicator {
    background: linear-gradient(135deg, #ffffff 0%, #f8f9fa 100%);
    color: #28a745;
}

.participant-card-body {
    display: flex;
    flex-direction: column;
    gap: 12px;
}

.participant-name {
    font-weight: 600;
    font-size: 1rem;
    color: #212529;
    line-height: 1.2;
}

.participant-card-item.selected .participant-name {
    color: white;
    font-weight: 700;
}

.participant-details-grid {
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: 8px;
}

.detail-badge {
    display: flex;
    align-items: center;
    gap: 6px;
    font-size: 0.75rem;
    padding: 4px 8px;
    border-radius: 8px;
    background: rgba(108, 117, 125, 0.1);
    color: #6c757d;
    transition: all 0.2s ease;
}

.detail-badge i {
    width: 12px;
    text-align: center;
}

.detail-badge span {
    flex: 1;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
}
.table-participants td{
    vertical-align: middle;
}
.detail-badge.club {
    background: #343a4012;
    color: #343a40;
}
td .detail-badge {
    display: inline-block;
}
.detail-badge.category {
    background: #1987541c;
    color: #198754;
}

.detail-badge.gender {
    background: rgba(220, 53, 69, 0.1);
    color: #dc3545;
}
.detail-badge.gender-male {
    background: lch(49 81.77 283.4 / 0.1);
    color: #0d6efd;
}
.detail-badge.year {
    background: rgba(108, 117, 125, 0.1);
    color: #6c757d;
}

.participant-card-item.selected .detail-badge {
    background: rgba(255, 255, 255, 0.2);
    color: rgba(255, 255, 255, 0.9);
}

.no-participants-message {
    background: white;
    border-radius: 12px;
    margin: 16px;
}

.participant-select-footer {
    background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);
    padding: 12px 16px;
    border-top: 1px solid #dee2e6;
}

/* Search bar styling */
.input-group .input-group-text {
    background: white;
    border-color: #ced4da;
}

#participantSearch {
    border-color: #ced4da;
}

#participantSearch:focus {
    border-color: #007bff;
    box-shadow: 0 0 0 0.2rem rgba(0, 123, 255, 0.25);
}

/* Selection status badge animation */
#participantStatusBadge {
    transition: all 0.3s ease;
}

#participantStatusBadge.has-selection {
    background: linear-gradient(135deg, #28a745 0%, #20c997 100%) !important;
    animation: pulse 1s ease-in-out;
}

@keyframes pulse {
    0% { transform: scale(1); }
    50% { transform: scale(1.1); }
    100% { transform: scale(1); }
}

/* Hide/show animation */
.participant-card-item.hidden {
    display: none;
}

.participant-card-item.show {
    animation: fadeInUp 0.3s ease;
}

@keyframes fadeInUp {
    from {
        opacity: 0;
        transform: translateY(20px);
    }
    to {
        opacity: 1;
        transform: translateY(0);
    }
}

/* Responsive design */
@media (max-width: 768px) {
    .participant-grid {
        grid-template-columns: 1fr;
        gap: 8px;
        padding: 12px;
    }
    
    .participant-card-item {
        padding: 12px;
    }
    
    .participant-details-grid {
        grid-template-columns: 1fr;
        gap: 6px;
    }
    
    .participant-bib-badge {
        font-size: 0.7rem;
        padding: 4px 8px;
        min-width: 40px;
    }
}

@media (max-width: 576px) {
    .participant-grid-container {
        max-height: 400px;
    }
    
    .participant-card-header {
        margin-bottom: 8px;
    }
    
    .participant-name {
        font-size: 0.9rem;
    }
    
    .detail-badge {
        font-size: 0.7rem;
        padding: 3px 6px;
    }
}

/* Scrollbar styling */
.participant-grid-container::-webkit-scrollbar {
    width: 8px;
}

.participant-grid-container::-webkit-scrollbar-track {
    background: #f1f1f1;
    border-radius: 4px;
}

.participant-grid-container::-webkit-scrollbar-thumb {
    background: linear-gradient(135deg, #6c757d 0%, #495057 100%);
    border-radius: 4px;
}

.participant-grid-container::-webkit-scrollbar-thumb:hover {
    background: linear-gradient(135deg, #495057 0%, #343a40 100%);
}
</style>
<script>
jQuery(function() {
    jQuery("#reorder-table tbody").sortable({
        helper: fixWidthHelper,
        update: function(event, ui) {
            const order = jQuery("#reorder-table tbody tr").map(function() {
                return jQuery(this).data("id");
            }).get();

            jQuery.ajax({
                url: "save_reorder.php",
                method: "POST",
                data: { order: order },
                success: function(response) {
                    console.log("Saved order:", order);
                    console.log("Saved order:", response);
                }
            });
        }
    }).disableSelection();

    function fixWidthHelper(e, ui) {
        ui.children().each(function() {
            jQuery(this).width(jQuery(this).width());
        });
        return ui;
    }
});
jQuery(function () {
    const $tbody = jQuery("#reorder-table tbody");

    $tbody.sortable({
        helper: function (e, item) {
            let selected = item.closest('tbody').find('input.bulk-check:checked').closest('tr');

            // If the dragged row is not selected, deselect others
            if (!item.find('input.bulk-check').is(':checked')) {
                selected = item;
                $tbody.find('input.bulk-check').prop('checked', false);
                item.find('input.bulk-check').prop('checked', true);
            }

            // Clone all selected rows for visual feedback
            const helper = jQuery('<tbody/>');
            selected.each(function () {
                helper.append(jQuery(this).clone().css('background', '#f0f0f0'));
            });

            item.data('multidrag', selected); // Store original selection
            return helper;
        },
        start: function (e, ui) {
            const selected = ui.item.data('multidrag');
            selected.css('opacity', 0.5);
        },
        stop: function (e, ui) {
            const selected = ui.item.data('multidrag');
            const targetIndex = ui.item.index();

            // Move all selected rows to the new index
            selected.css('opacity', 1);
            selected.detach();

            if (targetIndex === 0) {
                $tbody.prepend(selected);
            } else {
                $tbody.find('tr').eq(targetIndex - 1).after(selected);
            }

            // Send new order via AJAX
            const newOrder = $tbody.find('tr').map(function () {
                return jQuery(this).data("id");
            }).get();

            jQuery.ajax({
                url: "save_reorder.php",
                method: "POST",
                data: { order: newOrder },
                success: function (response) {
                    console.log("New order saved", newOrder);
                }
            });
        },
        cancel: 'input,button',
        items: '> tr'
    });
});
jQuery('#reverseSelectedBtn').on('click', function () {
    const $tbody = jQuery('#reorder-table tbody');
    const $selectedRows = $tbody.find('tr:visible').has('input.bulk-check:checked');

    if ($selectedRows.length < 2) {
        alert('Select at least 2 rows to reverse.');
        return;
    }

    // Get index of the first selected row
    const firstIndex = $selectedRows.first().index();

    // Detach and reverse
    const $reversed = jQuery($selectedRows.get().reverse());
    $selectedRows.remove();
    if (firstIndex === 0) {
        $tbody.prepend($reversed);
    } else {
        $tbody.find('tr').eq(firstIndex - 1).after($reversed);
    }

    // Renumber serials
    let serial = 1;
    $tbody.find('tr:visible').each(function () {
        jQuery(this).find('.serial-number').text(serial++);
    });

    // Save new order via AJAX
    const newOrder = $tbody.find('tr').map(function () {
        return jQuery(this).data('id');
    }).get();

    jQuery.ajax({
        url: 'save_reorder.php',
        method: 'POST',
        data: { order: newOrder },
        success: function (res) {
            console.log('Reversed order saved');
        }
    });
});
jQuery('#shuffleSelectedBtn').on('click', function () {
    const $tbody = jQuery('#reorder-table tbody');
    const $selectedRows = $tbody.find('tr:visible').has('input.bulk-check:checked');

    if ($selectedRows.length < 2) {
        alert('Select at least 2 rows to shuffle.');
        return;
    }

    // Get index of first selected row
    const firstIndex = $selectedRows.first().index();

    // Convert selected rows to array and shuffle it
    const rowsArray = $selectedRows.get();
    for (let i = rowsArray.length - 1; i > 0; i--) {
        const j = Math.floor(Math.random() * (i + 1));
        [rowsArray[i], rowsArray[j]] = [rowsArray[j], rowsArray[i]];
    }

    const $shuffled = jQuery(rowsArray);
    $selectedRows.remove();

    if (firstIndex === 0) {
        $tbody.prepend($shuffled);
    } else {
        $tbody.find('tr').eq(firstIndex - 1).after($shuffled);
    }

    // Renumber serials
    let serial = 1;
    $tbody.find('tr:visible').each(function () {
        jQuery(this).find('.serial-number').text(serial++);
    });

    // Save new order via AJAX
    const newOrder = $tbody.find('tr').map(function () {
        return jQuery(this).data('id');
    }).get();

    jQuery.ajax({
        url: 'save_reorder.php',
        method: 'POST',
        data: { order: newOrder },
        success: function (res) {
            console.log('Shuffled order saved');
            $shuffled.addClass('shuffled');
setTimeout(() => $shuffled.removeClass('shuffled'), 600);

        }
    });
});
function sortSelectedRows(comparator) {
    const $tbody = jQuery('#reorder-table tbody');
    const $selectedRows = $tbody.find('tr:visible').has('input.bulk-check:checked');

    if ($selectedRows.length < 2) {
        alert('Select at least 2 rows to sort.');
        return;
    }

    const firstIndex = $selectedRows.first().index();
    const rowsArray = $selectedRows.get();

    rowsArray.sort(comparator);
    const $sorted = jQuery(rowsArray);
    $selectedRows.remove();

    if (firstIndex === 0) {
        $tbody.prepend($sorted);
    } else {
        $tbody.find('tr').eq(firstIndex - 1).after($sorted);
    }

    // Renumber serials
    let serial = 1;
    $tbody.find('tr:visible').each(function () {
        jQuery(this).find('.serial-number').text(serial++);
    });

    // Save new order
    const newOrder = $tbody.find('tr').map(function () {
        return jQuery(this).data('id');
    }).get();

    jQuery.ajax({
        url: 'save_reorder.php',
        method: 'POST',
        data: { order: newOrder },
        success: function (res) {
            console.log('Sorted order saved');
        }
    });
}

// Sort Alphabetically (Last + First)
jQuery('#sortByNameBtn').on('click', function () {
    sortSelectedRows(function (a, b) {
        const nameA = jQuery(a).find('td').eq(4).text().toLowerCase();
        const nameB = jQuery(b).find('td').eq(4).text().toLowerCase();
        return nameA.localeCompare(nameB);
    });
});

// Sort by bib (numerically)
jQuery('#sortBybibBtn').on('click', function () {
    sortSelectedRows(function (a, b) {
        const bibA = parseInt(jQuery(a).find('td').eq(3).text(), 10);
        const bibB = parseInt(jQuery(b).find('td').eq(3).text(), 10);
        return bibA - bibB;
    });
});

// Sort by Year (youngest last)
jQuery('#sortByYearBtn').on('click', function () {
    sortSelectedRows(function (a, b) {
        const yearA = parseInt(jQuery(a).data('year'), 10);
        const yearB = parseInt(jQuery(b).data('year'), 10);
        return yearA - yearB;
    });
});

</script>
<script>
// Enhanced AJAX assignment with better UX
jQuery('#ajaxAssignBtn').on('click', function () {
    const $btn = jQuery(this);
    const form = jQuery('#ajaxAssignForm');
    const eventId = form.data('event');
    const heatNumber = form.find('[name=heat_number]').val();
    const participants = form.find('[name="participant_ids[]"] option:selected').map(function () {
        return this.value;
    }).get();

    if (!heatNumber) {
        alert('Please select a heat first.');
        document.getElementById('heat_number').focus();
        return;
    }
    
    if (participants.length === 0) {
        alert('Please select at least one participant to assign.');
        document.getElementById('participantSelect').focus();
        return;
    }

    // Show loading state
    $btn.addClass('loading').prop('disabled', true);
    const originalText = $btn.html();

    jQuery.ajax({
        url: 'ajax_assing.php',
        method: 'POST',
        data: {
            event_id: eventId,
            heat_number: heatNumber,
            participant_ids: participants
        },
        dataType: 'json',
        success: function (response) {
            if (response.status === 'success') {
                // Show success message
                $btn.removeClass('loading btn-success').addClass('btn-outline-success').html('<i class="fas fa-check me-2"></i>Success!');
                
                // Show detailed success message
                const participantCount = participants.length;
                const heatName = jQuery('#heat_number option:selected').text();
                
                alert(`✅ Successfully assigned ${participantCount} participant(s) to ${heatName}!\n\n${response.message}`);
                
                // Reload page after short delay
                setTimeout(() => {
                    window.location.reload();
                }, 1000);
            } else {
                throw new Error(response.message || 'Assignment failed');
            }
        },
        error: function (xhr, status, error) {
            console.error('AJAX Error:', xhr.responseText);
            let errorMessage = 'Assignment failed. Please try again.';
            
            try {
                const response = JSON.parse(xhr.responseText);
                errorMessage = response.message || errorMessage;
            } catch (e) {
                if (xhr.responseText) {
                    errorMessage = 'Server error: ' + xhr.responseText.substring(0, 100);
                }
            }
            
            alert('❌ Error: ' + errorMessage);
        },
        complete: function () {
            // Restore button state
            $btn.removeClass('loading').prop('disabled', false);
            if (!$btn.hasClass('btn-outline-success')) {
                $btn.html(originalText);
            }
        }
    });
});

// Auto-clear selection after successful assignment
function clearFormAfterSuccess() {
    document.getElementById('heat_number').value = '';
    clearSelection();
    clearAllFilters();
}
</script>
<script>
    jQuery(document).ready(function () {
    // Master "select all" checkbox — only visible rows
    jQuery('#bulk-check-master').on('change', function () {
        const checked = this.checked;
        jQuery('#reorder-table tbody tr:visible .bulk-check').each(function () {
            this.checked = checked;
            jQuery(this).closest('tr').toggleClass('selected-row', checked);
        });
    });

    // Toggle row highlight on individual row selection
    jQuery(document).on('change', '.bulk-check', function () {
        jQuery(this).closest('tr').toggleClass('selected-row', this.checked);
    });
});
    </script>
   

    <div class="modal fade" id="assignbibModal" tabindex="-1" aria-labelledby="assignbibModalLabel" aria-hidden="true">
  <div class="modal-dialog">
    <div class="modal-content">
      <form id="assignbibForm">
        <div class="modal-header">
          <h5 class="modal-title" id="assignbibModalLabel">Assign bib Numbers</h5>
          <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
        </div>
        <div class="modal-body">
          <div class="mb-3">
            <label for="bib_series_id" class="form-label">Select bib Series</label>
            <select name="bib_series_id" id="bib_series_id" class="form-select" required>
              <option value="">-- Choose Series --</option>
              <?php foreach ($bib_series as $series): ?>
                <option value="<?= $series['id'] ?>" data-start="<?= $series['start_number'] ?>" data-end="<?= $series['end_number'] ?>">
                  <?= htmlspecialchars($series['name']) ?> (<?= $series['start_number'] ?>–<?= $series['end_number'] ?>)
                </option>
              <?php endforeach; ?>
            </select>
          </div>
          
          <div class="mb-3">
            <label for="start_number" class="form-label">Start bib Number</label>
            <input type="number" name="start_number" id="start_number" class="form-control" placeholder="Auto from series" min="1">
            <small class="form-text text-muted">Leave empty to use next available from series</small>
          </div>
          
          <div class="form-check mb-3">
            <input type="checkbox" name="overwrite_existing" id="overwrite_existing" class="form-check-input">
            <label class="form-check-label" for="overwrite_existing">
              Overwrite existing bib numbers
            </label>
            <small class="form-text text-muted d-block">If unchecked, only participants without bib will be assigned</small>
          </div>
        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
          <button type="submit" class="btn btn-primary">Assign bibs</button>
        </div>
      </form>
    </div>
  </div>
</div>
 <script>
// Auto-fill start number when series is selected
jQuery('#bib_series_id').on('change', function() {
    const selectedOption = jQuery(this).find('option:selected');
    const startNumber = selectedOption.data('start');
    if (startNumber) {
        jQuery('#start_number').attr('placeholder', 'Auto from series (' + startNumber + ')');
    }
});
// Replace the old #promoteToHeatBtn handler with this:
jQuery('#promoteToHeatBtn').on('click', function () {
    jQuery('#promoteToHeatModal').modal('show');
});


jQuery('#assignbibForm').on('submit', function (e) {
    e.preventDefault();

    const selectedIds = jQuery('#reorder-table tbody tr:visible .bulk-check:checked')
        .map(function () {
            return jQuery(this).val();
        }).get();

    const seriesId = jQuery('#bib_series_id').val();
    const startNumber = jQuery('#start_number').val();
    const overwriteExisting = jQuery('#overwrite_existing').is(':checked');
    const eventId = <?= json_encode($selected_event) ?>;

    if (!seriesId || selectedIds.length === 0) {
        alert('Please select at least one participant and a bib series.');
        return;
    }

    jQuery.ajax({
        url: 'ajax_assign_bib.php',
        method: 'POST',
        data: {
            participant_ids: selectedIds,
            bib_series_id: seriesId,
            start_number: startNumber,
            overwrite_existing: overwriteExisting ? 1 : 0,
            event_id: eventId
        },
        success: function (response) {
            try {
                const res = JSON.parse(response);
                if (res.status === 'success') {
                    alert(res.message);
                    location.reload();
                } else {
                    alert(res.message || 'An error occurred.');
                }
            } catch (e) {
                alert('Invalid response.');
                console.error(response);
            }
        },
        error: function () {
            alert('AJAX request failed.');
        }
    });
});
</script>
<!-- Add this modal after the Move to Heat Modal -->
<div class="modal fade" id="promoteToHeatModal" tabindex="-1" aria-labelledby="promoteToHeatModalLabel" aria-hidden="true">
  <div class="modal-dialog">
    <div class="modal-content">
      <form id="promoteToHeatForm">
        <div class="modal-header">
          <h5 class="modal-title" id="promoteToHeatModalLabel">Promote Participants to Heat</h5>
          <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
        </div>
        <div class="modal-body">
          <div class="mb-3">
            <label for="promote_target_heat" class="form-label">Target Heat</label>
            <select name="promote_target_heat" id="promote_target_heat" class="form-select" required>
              <option value="">-- Select Heat --</option>
              <?php foreach ($heat_options as $heat): ?>
                <option value="<?= $heat['heat_number'] ?>">
                  <?= $heat['heat_number'] ?><?= $heat['heat_name'] ? ' – ' . htmlspecialchars($heat['heat_name']) : '' ?>
                </option>
              <?php endforeach; ?>
            </select>
          </div>
          <div class="alert alert-warning">
            <small>
              Participants will be promoted to the selected heat based on promotion logic/results.
            </small>
          </div>
        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
          <button type="submit" class="btn btn-warning">Promote to Heat</button>
        </div>
      </form>
    </div>
  </div>
</div>
<!-- Move to Heat Modal -->
<div class="modal fade" id="moveToHeatModal" tabindex="-1" aria-labelledby="moveToHeatModalLabel" aria-hidden="true">
  <div class="modal-dialog">
    <div class="modal-content">
      <form id="moveToHeatForm">
        <div class="modal-header">
          <h5 class="modal-title" id="moveToHeatModalLabel">Move/Copy Selected to Heat</h5>
          <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
        </div>
        <div class="modal-body">
          <div class="mb-3">
            <label for="target_heat_number" class="form-label">Target Heat</label>
            <select name="target_heat_number" id="target_heat_number" class="form-select" required>
              <option value="">-- Select Heat --</option>
              <?php foreach ($heat_options as $heat): ?>
                <option value="<?= $heat['heat_number'] ?>">
                  <?= $heat['heat_number'] ?><?= $heat['heat_name'] ? ' – ' . htmlspecialchars($heat['heat_name']) : '' ?>
                </option>
              <?php endforeach; ?>
            </select>
          </div>
          
          <div class="mb-3">
            <label class="form-label">Action</label>
            <div class="form-check">
              <input type="radio" name="action_type" id="action_move" value="move" class="form-check-input" checked>
              <label class="form-check-label" for="action_move">
                <strong>Move</strong> - Transfer participants to target heat (remove from current heat)
              </label>
            </div>
            <div class="form-check">
              <input type="radio" name="action_type" id="action_copy" value="copy" class="form-check-input">
              <label class="form-check-label" for="action_copy">
                <strong>Copy</strong> - Duplicate participants in target heat (keep in current heat)
              </label>
            </div>            
          </div>
          
          <div class="alert alert-info">
            <small id="actionDescription">Selected participants will be moved to the target heat.</small>
          </div>
        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
          <button type="submit" class="btn btn-primary" id="actionSubmitBtn">Move to Heat</button>
        </div>
      </form>
    </div>
  </div>
</div>
<script>
    jQuery('#promoteToHeatForm').on('submit', function (e) {
    e.preventDefault();

    const targetHeat = jQuery('#promote_target_heat').val();
    const eventId = <?= json_encode($selected_event) ?>;

    if (!targetHeat) {
        alert('Please select a target heat.');
        return;
    }

    if (!confirm(`Promote participants to Heat ${targetHeat}?`)) return;

    const $btn = jQuery('#promoteToHeatForm button[type="submit"]');
    $btn.prop('disabled', true).html('<i class="fas fa-spinner fa-spin me-1"></i>Promoting...');

    jQuery.ajax({
        url: '../api/summary_table_api.php',
        method: 'GET',
        data: {
            action: 'promote',
            event_id: eventId,
            target_heat: targetHeat
        },
        dataType: 'json',
        success: function (response) {
            alert((response.status === 'success' ? '✅ ' : '❌ ') + response.message);
            if (response.status === 'success') {
                location.reload();
            }
        },
        error: function (xhr) {
            alert('AJAX error: ' + xhr.responseText);
        },
        complete: function () {
            $btn.prop('disabled', false).html('Promote to Heat');
            jQuery('#promoteToHeatModal').modal('hide');
        }
    });
});</script>
<script>
// Update action description and button text based on selected radio
jQuery('input[name="action_type"]').on('change', function() {
    const actionType = jQuery(this).val();
    const description = jQuery('#actionDescription');
    const submitBtn = jQuery('#actionSubmitBtn');
    
    if (actionType === 'move') {
        description.text('Selected participants will be moved to the target heat.');
        submitBtn.text('Move to Heat');
        submitBtn.removeClass('btn-success').addClass('btn-primary');
    } else if (actionType === 'copy') {
        description.text('Selected participants will be copied to the target heat (originals remain).');
        submitBtn.text('Copy to Heat');
        submitBtn.removeClass('btn-primary').addClass('btn-success');
    } else if (actionType === 'promote') {
        description.text('Participants will be promoted to the target heat based on heat flow settings and results from the linked heat.');
        submitBtn.text('Promote to Heat');
        submitBtn.removeClass('btn-primary btn-success').addClass('btn-warning');
    }
});

jQuery('#moveToHeatForm').on('submit', function (e) {
    e.preventDefault();

    const selectedIds = jQuery('#reorder-table tbody tr:visible .bulk-check:checked')
        .map(function () {
            return jQuery(this).val(); // This gets the event_participants.id
        }).get();

    const targetHeat = jQuery('#target_heat_number').val();
    const actionType = jQuery('input[name="action_type"]:checked').val();
    const eventId = <?= json_encode($selected_event) ?>;

    if (!targetHeat) {
        alert('Please select a target heat.');
        return;
    }
    if (actionType !== 'promote' && selectedIds.length === 0) {
        alert('Please select at least one participant.');
        return;
    }

    if (!targetHeat || selectedIds.length === 0) {
        alert('Please select a target heat and at least one participant.');
        return;
    }

    const actionText = actionType === 'move' ? 'move' : 'copy';
    if (!confirm(`${actionText.charAt(0).toUpperCase() + actionText.slice(1)} ${selectedIds.length} selected participants to Heat ${targetHeat}?`)) {
        return;
    }

    jQuery.ajax({
        url: 'ajax_move_to_heat.php',
        method: 'POST',
        data: {
            event_participant_ids: selectedIds,
            target_heat: targetHeat,
            action_type: actionType,
            event_id: eventId
        },
        dataType: 'json',
        success: function (response) {
            if (response.status === 'success') {
                alert(response.message);
                jQuery('#moveToHeatModal').modal('hide');
                location.reload();
            } else {
                alert('Error: ' + response.message);
            }
        },
        error: function (xhr, status, error) {
            alert('AJAX request failed: ' + error);
            console.error(xhr.responseText);
        }
    });
});
</script>

</body>
</html>
