<?php
include_once '../includes/auth.php';
include_once '../includes/db.php';
// filepath: c:\stylescore2025\htdocs\v2\admin\heat_management_modal.php
// This file can be included directly or loaded via AJAX
/*

Usage Examples:
1. Standalone Page:
http://yoursite.com/admin/heat_management_modal.php?event_id=123&standalone=1
2. Include in any page:
<?php
include 'heat_management_helper.php';
includeHeatManagementModal($event_id);
renderHeatManagementTrigger($event_id);
3. Load via AJAX:
<?php
echo '<div id="heatModalContainer"></div>';
loadHeatManagementModalViaAJAX('heatModalContainer', $event_id);
4. Custom trigger button:
<?php
renderHeatManagementTrigger($event_id, 'heatManagementModal', 'btn btn-success btn-lg', '<i class="fas fa-fire"></i> Manage Heats');

This modular approach allows you to:

Use the heat management modal on any page
Load it standalone for full-screen management
Include it via AJAX for dynamic loading
Customize trigger buttons and styling
Maintain consistent functionality across all implementations


*/
$event_id = $_GET['event_id'] ?? $_POST['event_id'] ?? null;
$standalone = isset($_GET['standalone']) || isset($_POST['standalone']);

// If this is a standalone page, include headers
if ($standalone): ?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Heat Management</title>
    <!-- style skin holder -->

    <link rel="stylesheet" href="/v2/assets/css/backgrounds.css">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">

    <script src="/v2/assets/js/notification_manager.js"></script>
    <style>
        
        .standalone-container {
            max-width: 1200px;
            margin: 0 auto;
        }
        .modal-content {
            border-radius: 15px;
            border: none;
            box-shadow: 0 20px 40px rgba(0,0,0,0.3);
             background: white;
        }
        form#heatUpdateForm {
   
    padding: 25px;
}
    </style>
</head>
<body class="body-bg-aurora-bright">
    <?php include '../menu.php'; ?>
    <div class="standalone-container">
        <div class="modal-content">
<?php endif; ?>

<!-- Heat Management Modal Content -->
<div class="modal-header bg-primary text-white py-2">
    <div class="d-flex align-items-center justify-content-between w-100">
        <div class="d-flex align-items-center">
            <div class="me-2">
                <i class="fas fa-tower-broadcast fs-4"></i>
            </div>
            <div>
                <h5 class="mb-0">Competition Command Center</h5>
                <?php if ($event_id): ?>
                    <small class="opacity-75">Event ID: <?= htmlspecialchars($event_id) ?> • Real-time Management</small>
                <?php endif; ?>
            </div>
        </div>
        <div class="d-flex align-items-center gap-2">
            <span class="badge bg-success live-pulse px-2 py-1">
                <i class="fas fa-circle me-1"></i>LIVE
            </span>
            <?php if (!$standalone): ?>
                <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Close"></button>
            <?php else: ?>
                <a href="event_dashboard.php?event_id=<?= htmlspecialchars($event_id) ?>" class="btn btn-outline-light btn-sm">
                    <i class="fas fa-arrow-left me-1"></i>Back
                </a>
            <?php endif; ?>
        </div>
    </div>
</div>

<div class="modal-body p-0">
    <!-- Loading State -->
    <div id="modalLoadingState" class="text-center py-3">
        <div class="spinner-border text-primary" role="status">
            <span class="visually-hidden">Loading...</span>
        </div>
        <p class="mt-2 text-muted small">Loading competition data...</p>
    </div>
    
    <!-- Error State -->
    <div id="modalErrorState" class="alert alert-danger m-2" style="display: none;">
        <i class="fas fa-exclamation-triangle me-2"></i>
        <span id="modalErrorMessage">Error loading data</span>
        <button class="btn btn-outline-danger btn-sm ms-2" onclick="loadHeatManagementData()">
            <i class="fas fa-redo me-1"></i>Retry
        </button>
    </div>
    
    <!-- Command Center Interface -->
    <div id="heatManagementForm" style="display: none;">
        <!-- Live Status Dashboard -->
        <div class="bg-light border-bottom p-2">
            <div class="d-flex justify-content-between align-items-center mb-2">
                <h6 class="mb-0 fw-bold text-primary">
                    <i class="fas fa-broadcast-tower me-1"></i>Live Status
                </h6>
                <div class="d-flex gap-1">
                    <span class="badge bg-success live-pulse px-2 py-1" id="liveStatusIndicator">
                        <i class="fas fa-circle me-1"></i>LIVE
                    </span>
                    <button class="btn btn-outline-primary btn-sm px-2 py-1" id="pauseAutoUpdateBtn">
                        <i class="fas fa-pause"></i>
                    </button>
                    <button class="btn btn-outline-primary btn-sm px-2 py-1" id="refreshStatusBtn">
                        <i class="fas fa-sync-alt"></i>
                    </button>
                </div>
            </div>
            <div id="liveStatusGrid" class="row g-2">
                <!-- Live status cards will be populated here -->
            </div>
        </div>

        <!-- Competition Control Panel -->
        <div class="bg-light p-2">
            <h6 class="mb-2 fw-bold text-primary">
                <i class="fas fa-sliders-h me-1"></i>Control Panel
            </h6>
            <div class="row g-2">
                <!-- Heat & Run Control -->
                <div class="col-md-6">
                    <div class="border-0 shadow-none card h-100">
                        <div class="border-0 shadow-none card-header bg-primary text-white py-2">
                            <h6 class="mb-0 small"><i class="fas fa-fire me-1"></i>Heat & Run</h6>
                        </div>
                        <div class="border-0 shadow-none card-body p-2">
                            <div class="mb-2">
                                <label class="form-label small fw-bold mb-1">Active Heat</label>
                                <select class="form-select form-select-sm" id="activeHeatSelect" name="active_heat">
                                    <option value="">Select Heat</option>
                                </select>
                            </div>
                            <div class="mb-2">
                                <label class="form-label small fw-bold mb-1">Active Run</label>
                                <select class="form-select form-select-sm" id="activeRunSelect" name="active_run">
                                    <option value="1">Run 1</option>
                                </select>
                            </div>
                            <div class="d-grid">
                                <button type="button" class="btn btn-primary btn-sm" id="activateHeatBtn">
                                    <i class="fas fa-play me-1"></i>Activate
                                </button>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Participant Control -->
                <div class="col-md-6">
                    <div class="border-0 shadow-none card h-100">
                        <div class="border-0 shadow-none card-header bg-success text-white py-2">
                            <h6 class="mb-0 small"><i class="fas fa-user-check me-1"></i>Participants</h6>
                        </div>
                        <div class="border-0 shadow-none card-body p-2">
                            <div class="mb-2">
                                <label class="form-label small fw-bold mb-1">On Start</label>
                                <div class="input-group input-group-sm">
                                    <span class="input-group-text">#</span>
                                    <input type="number" class="form-control" id="bibOnStart" name="bib_on_start" placeholder="BIB">
                                    <button type="button" class="btn btn-outline-success btn-sm" id="setNextFromListBtn">
                                        <i class="fas fa-list"></i>
                                    </button>
                                </div>
                            </div>
                            <div class="mb-2">
                                <label class="form-label small fw-bold mb-1">Latest</label>
                                <div class="input-group input-group-sm">
                                    <span class="input-group-text">#</span>
                                    <input type="number" class="form-control" id="bibLatestRun" name="bib_latest_on_run" placeholder="BIB">
                                    <button type="button" class="btn btn-outline-secondary btn-sm" id="clearLatestBtn">
                                        <i class="fas fa-times"></i>
                                    </button>
                                </div>
                            </div>
                            <div class="form-check form-check-sm">
                                <input class="form-check-input" type="checkbox" id="autoNextParticipant" checked>
                                <label class="form-check-label small" for="autoNextParticipant">
                                    Auto-advance
                                </label>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Quick Actions Panel -->
        <div class="bg-warning bg-opacity-10 p-2">
            <h6 class="mb-2 fw-bold text-warning">
                <i class="fas fa-bolt me-1"></i>Quick Actions
            </h6>
            <div class="row g-1">
                <div class="col-6 col-md-3">
                    <button type="button" class="btn btn-warning w-100 py-2" id="markStartedBtn">
                        <i class="fas fa-play d-block mb-1"></i>
                        <small>Started</small>
                    </button>
                </div>
                <div class="col-6 col-md-3">
                    <button type="button" class="btn btn-success w-100 py-2" id="markCompletedBtn">
                        <i class="fas fa-flag-checkered d-block mb-1"></i>
                        <small>Completed</small>
                    </button>
                </div>
                <div class="col-6 col-md-3">
                    <button type="button" class="btn btn-info w-100 py-2" id="nextParticipantBtn">
                        <i class="fas fa-step-forward d-block mb-1"></i>
                        <small>Next</small>
                    </button>
                </div>
                <div class="col-6 col-md-3">
                    <button type="button" class="btn btn-danger w-100 py-2" id="emergencyStopBtn">
                        <i class="fas fa-stop d-block mb-1"></i>
                        <small>Stop</small>
                    </button>
                </div>
            </div>
        </div>

        <!-- Enhanced Participant Queue -->
        <div class="p-3 bg-light border-top">
            <div class="d-flex justify-content-between align-items-center mb-3">
                <h5 class="mb-0 fw-bold text-primary">
                    <i class="fas fa-users me-2"></i>Participant Queue
                </h5>
                <div class="btn-group" role="group">
                    <input type="radio" class="btn-check" name="queueMode" id="queueModeStartList" value="start_list" checked>
                    <label class="btn btn-outline-primary btn-lg" for="queueModeStartList">
                        <i class="fas fa-list-ol me-1"></i>Start List
                    </label>
                    <input type="radio" class="btn-check" name="queueMode" id="queueModeManual" value="manual">
                    <label class="btn btn-outline-primary btn-lg" for="queueModeManual">
                        <i class="fas fa-hand-paper me-1"></i>Manual
                    </label>
                </div>
            </div>
            
            <!-- Current & Next Participants - Touch Optimized -->
            <div class="row g-3 mb-4">
                <!-- Currently Performing -->
                <div class="col-lg-4 col-md-6">
                    <div class="card border-success shadow-sm h-100">
                        <div class="card-header bg-success text-white py-3 text-center">
                            <h5 class="mb-0"><i class="fas fa-running me-2"></i>PERFORMING NOW</h5>
                        </div>
                        <div class="card-body p-3" id="performingParticipantCard">
                            <div class="text-center text-muted py-4">
                                <i class="fas fa-running display-4 mb-3 d-block"></i>
                                <h6 class="mb-0">No one performing</h6>
                            </div>
                        </div>
                    </div>
                </div>
                
                <!-- On Start Gate -->
                <div class="col-lg-4 col-md-6">
                    <div class="card border-warning shadow-sm h-100">
                        <div class="card-header bg-warning text-dark py-3 text-center">
                            <h5 class="mb-0"><i class="fas fa-play me-2"></i>ON START GATE</h5>
                        </div>
                        <div class="card-body p-3" id="currentParticipantCard">
                            <div class="text-center text-muted py-4">
                                <i class="fas fa-user-slash display-4 mb-3 d-block"></i>
                                <h6 class="mb-0">No participant on start</h6>
                                <button class="btn btn-outline-warning mt-2" onclick="selectFromQueue('current')">
                                    <i class="fas fa-hand-pointer me-1"></i>Select from Queue
                                </button>
                            </div>
                        </div>
                    </div>
                </div>
                
                <!-- Next Up -->
                <div class="col-lg-4 col-md-6">
                    <div class="card border-info shadow-sm h-100">
                        <div class="card-header bg-info text-white py-3 text-center">
                            <h5 class="mb-0"><i class="fas fa-clock me-2"></i>NEXT UP</h5>
                        </div>
                        <div class="card-body p-3" id="nextParticipantCard">
                            <div class="text-center text-muted py-4">
                                <i class="fas fa-hourglass-half display-4 mb-3 d-block"></i>
                                <h6 class="mb-0">No next participant</h6>
                                <button class="btn btn-outline-info mt-2" onclick="selectFromQueue('next')">
                                    <i class="fas fa-hand-pointer me-1"></i>Select from Queue
                                </button>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            
            <!-- Enhanced Queue List - Touch Friendly -->
            <div class="card shadow-sm">
                <div class="card-header bg-secondary text-white py-3">
                    <div class="d-flex justify-content-between align-items-center">
                        <h5 class="mb-0"><i class="fas fa-list me-2"></i>Live Participant Status</h5>
                        <div class="d-flex gap-2">
                            <span class="badge bg-warning text-dark px-2 py-1">
                                <i class="fas fa-play me-1"></i>On Start Gate
                            </span>
                            <span class="badge bg-success px-2 py-1">
                                <i class="fas fa-running me-1"></i>Performing
                            </span>
                            <button class="btn btn-outline-light btn-sm" id="refreshQueueBtn">
                                <i class="fas fa-sync-alt me-1"></i>Refresh
                            </button>
                        </div>
                    </div>
                </div>
                <div class="card-body p-0">
                    <div id="extendedQueueList" class="scrollable-area" style="max-height: 500px; overflow-y: auto;">
                        <!-- Extended queue will be populated here -->
                    </div>
                </div>
            </div>
        </div>

        <!-- Enhanced Participant List - Matching Main Style -->
        <div id="participantListSection" style="display: none;">
            <div class="p-3 border-top bg-light">
                <div class="d-flex justify-content-between align-items-center mb-3">
                    <h5 class="mb-0 fw-bold text-primary">
                        <i class="fas fa-users me-2"></i>All Participants - Full Heat View
                    </h5>
                    <div class="d-flex gap-2">
                        <button class="btn btn-outline-primary btn-sm" id="filterActiveBtn">
                            <i class="fas fa-filter me-1"></i>Show Active Only
                        </button>
                        <button class="btn btn-outline-secondary btn-sm" id="toggleParticipantListBtn">
                            <i class="fas fa-eye-slash me-1"></i>Hide
                        </button>
                    </div>
                </div>
                
                <!-- Status Legend -->
                <div class="row g-2 mb-3">
                    <div class="col-auto">
                        <span class="badge bg-warning text-dark px-2 py-1">
                            <i class="fas fa-play me-1"></i>On Start Gate
                        </span>
                    </div>
                    <div class="col-auto">
                        <span class="badge bg-success px-2 py-1">
                            <i class="fas fa-running me-1"></i>Performing
                        </span>
                    </div>
                    <div class="col-auto">
                        <span class="badge bg-info px-2 py-1">
                            <i class="fas fa-clock me-1"></i>Ready/Waiting
                        </span>
                    </div>
                    <div class="col-auto">
                        <span class="badge bg-secondary px-2 py-1">
                            <i class="fas fa-check me-1"></i>Completed
                        </span>
                    </div>
                </div>
                
                <div id="allParticipantsGrid" class="row g-3">
                    <!-- All participants will be populated here with enhanced styling -->
                </div>
            </div>
        </div>

        <!-- Quick Notification Panel -->
        <div class="p-3 bg-gradient bg-primary bg-opacity-10">
            <h5 class="mb-3 fw-bold text-primary">
                <i class="fas fa-bell me-2"></i>Quick Notifications
            </h5>
            <div class="row g-2">
                <div class="col-6 col-md-4">
                    <button type="button" class="btn btn-info w-100 py-3 quick-notify-btn" data-type="heat_starting">
                        <i class="fas fa-fire display-6 d-block mb-2"></i>
                        <strong>Heat Starting</strong>
                        <small class="d-block">Notify heat is about to start</small>
                    </button>
                </div>
                <div class="col-6 col-md-4">
                    <button type="button" class="btn btn-warning w-100 py-3 quick-notify-btn" data-type="participant_ready">
                        <i class="fas fa-user-check display-6 d-block mb-2"></i>
                        <strong>Get Ready</strong>
                        <small class="d-block">Next participant prepare</small>
                    </button>
                </div>
                <div class="col-6 col-md-4">
                    <button type="button" class="btn btn-success w-100 py-3 quick-notify-btn" data-type="scores_ready">
                        <i class="fas fa-clipboard-check display-6 d-block mb-2"></i>
                        <strong>Scores Ready</strong>
                        <small class="d-block">Results available</small>
                    </button>
                </div>
                <div class="col-6 col-md-4">
                    <button type="button" class="btn btn-danger w-100 py-3 quick-notify-btn" data-type="delay">
                        <i class="fas fa-pause-circle display-6 d-block mb-2"></i>
                        <strong>Delay</strong>
                        <small class="d-block">Competition delayed</small>
                    </button>
                </div>
                <div class="col-6 col-md-4">
                    <button type="button" class="btn btn-secondary w-100 py-3 quick-notify-btn" data-type="break">
                        <i class="fas fa-coffee display-6 d-block mb-2"></i>
                        <strong>Break</strong>
                        <small class="d-block">Taking a break</small>
                    </button>
                </div>
                <div class="col-6 col-md-4">
                    <button type="button" class="btn btn-primary w-100 py-3 quick-notify-btn" data-type="custom">
                        <i class="fas fa-edit display-6 d-block mb-2"></i>
                        <strong>Custom</strong>
                        <small class="d-block">Send custom message</small>
                    </button>
                </div>
            </div>
        </div>
    </div>
</div>

<div class="modal-footer bg-light border-top py-3">
    <div class="d-flex justify-content-between w-100 align-items-center">
        <div class="d-flex gap-2">
            <?php if ($standalone): ?>
                <button type="button" class="btn btn-outline-secondary btn-sm" onclick="window.history.back()">
                    <i class="fas fa-arrow-left me-1"></i>Back
                </button>
            <?php else: ?>
                <button type="button" class="btn btn-secondary btn-sm" data-bs-dismiss="modal">
                    <i class="fas fa-times me-1"></i>Close
                </button>
            <?php endif; ?>
            <button type="button" class="btn btn-outline-primary btn-sm" id="toggleParticipantListTrigger">
                <i class="fas fa-table me-1"></i>Show All
            </button>
        </div>
        
        <div class="d-flex gap-2">
            <button type="button" class="btn btn-outline-info btn-sm" id="clearNotificationsBtn">
                <i class="fas fa-bell-slash me-1"></i>Clear
            </button>
            <button type="button" class="btn btn-warning btn-sm" id="deactivateAllBtn">
                <i class="fas fa-power-off me-1"></i>Stop
            </button>
            <button type="button" class="btn btn-info btn-sm" id="refreshDataBtn">
                <i class="fas fa-sync-alt me-1"></i>Refresh
            </button>
            <button type="button" class="btn btn-success" id="saveHeatSettings">
                <i class="fas fa-broadcast-tower me-1"></i>Apply Changes
            </button>
        </div>
    </div>
</div>

<!-- CSS Styles -->
<style>
    /* Minimal custom styles - mostly Bootstrap native */
    .command-section {
        border-bottom: 1px solid #dee2e6;
    }
    
    .command-section:last-child {
        border-bottom: none;
    }
    
    /* Live pulse animation */
    .live-pulse {
        animation: pulse-live 2s infinite;
    }
    
    .live-paused {
        animation: blink-paused 1s infinite;
    }
    
    @keyframes pulse-live {
        0% { opacity: 1; }
        50% { opacity: 0.7; }
        100% { opacity: 1; }
    }
    
    @keyframes blink-paused {
        0% { opacity: 1; }
        50% { opacity: 0.4; }
        100% { opacity: 1; }
    }
    
    /* Enhanced participant cards */
    .participant-card.current {
        border-color: var(--bs-warning) !important;
        background-color: rgba(255, 193, 7, 0.05);
    }
    
    .participant-card.next {
        border-color: var(--bs-info) !important;
        background-color: rgba(13, 202, 240, 0.05);
    }
    
    .participant-avatar {
        width: 50px;
        height: 50px;
        border-radius: 50%;
        background: var(--bs-secondary);
        display: flex;
        align-items: center;
        justify-content: center;
        color: white;
        font-weight: bold;
        font-size: 1.1rem;
    }
    
    /* Touch-friendly participant queue items */
    .queue-participant-item {
        display: flex;
        align-items: center;
        padding: 15px;
        margin-bottom: 2px;
        background: white;
        border-left: 4px solid #dee2e6;
        transition: all 0.2s ease;
        cursor: pointer;
        min-height: 80px;
        border-radius: 8px;
        box-shadow: 0 2px 4px rgba(0,0,0,0.05);
    }
    
    .queue-participant-item:hover {
        background: #f8f9fa;
        border-left-color: var(--bs-primary);
        transform: translateX(5px);
        box-shadow: 0 4px 8px rgba(0,0,0,0.1);
    }
    
    .queue-participant-item.selectable:hover {
        background: #e3f2fd;
        border-left-color: var(--bs-info);
    }
    
    /* Enhanced status styling for clear identification */
    .queue-participant-item.on-start-gate {
        background: linear-gradient(135deg, rgba(255, 193, 7, 0.15), rgba(255, 193, 7, 0.05));
        border-left-color: var(--bs-warning);
        border-left-width: 6px;
        animation: pulse-start-gate 2s infinite;
    }
    
    .queue-participant-item.performing {
        background: linear-gradient(135deg, rgba(25, 135, 84, 0.15), rgba(25, 135, 84, 0.05));
        border-left-color: var(--bs-success);
        border-left-width: 6px;
        animation: pulse-performing 1.5s infinite;
    }
    
    @keyframes pulse-start-gate {
        0% { box-shadow: 0 0 0 0 rgba(255, 193, 7, 0.4); }
        70% { box-shadow: 0 0 0 10px rgba(255, 193, 7, 0); }
        100% { box-shadow: 0 0 0 0 rgba(255, 193, 7, 0); }
    }
    
    @keyframes pulse-performing {
        0% { box-shadow: 0 0 0 0 rgba(25, 135, 84, 0.4); }
        70% { box-shadow: 0 0 0 10px rgba(25, 135, 84, 0); }
        100% { box-shadow: 0 0 0 0 rgba(25, 135, 84, 0); }
    }
    
    .queue-participant-item.current {
        background: rgba(255, 193, 7, 0.1);
        border-left-color: var(--bs-warning);
    }
    
    .queue-participant-item.next {
        background: rgba(13, 202, 240, 0.1);
        border-left-color: var(--bs-info);
    }
    
    .queue-participant-item.completed {
        background: rgba(108, 117, 125, 0.1);
        border-left-color: var(--bs-secondary);
        opacity: 0.8;
    }
    
    .queue-participant-bib {
        width: 50px;
        height: 50px;
        border-radius: 50%;
        background: var(--bs-primary);
        color: white;
        display: flex;
        align-items: center;
        justify-content: center;
        font-weight: bold;
        font-size: 1.1rem;
        margin-right: 15px;
        cursor: pointer;
        transition: all 0.2s ease;
    }
    
    .queue-participant-bib:hover {
        background: var(--bs-primary-dark, #0a58ca);
        transform: scale(1.1);
    }
    
    .queue-participant-info {
        flex-grow: 1;
        min-width: 0;
    }
    
    .queue-participant-name {
        font-weight: bold;
        font-size: 1.1rem;
        margin-bottom: 5px;
    }
    
    .queue-participant-details {
        font-size: 0.9rem;
        color: #6c757d;
    }
    
    .queue-participant-actions {
        display: flex;
        gap: 8px;
        margin-left: 10px;
    }
    
    /* Quick notification buttons */
    .quick-notify-btn {
        min-height: 120px;
        font-size: 0.9rem;
        transition: all 0.2s ease;
        border-width: 2px;
    }
    
    .quick-notify-btn:hover {
        transform: translateY(-2px);
        box-shadow: 0 4px 12px rgba(0,0,0,0.15);
    }
    
    .quick-notify-btn:active {
        transform: translateY(0);
    }
    
    /* Touch-friendly buttons */
    .btn-touch {
        min-height: 50px;
        font-size: 1.1rem;
        padding: 12px 20px;
    }
    
    .btn-touch-lg {
        min-height: 60px;
        font-size: 1.2rem;
        padding: 15px 25px;
    }
    
    /* Improved BIB number styling */
    .bib-number {
        display: inline-flex;
        align-items: center;
        justify-content: center;
        width: 40px;
        height: 40px;
        background: var(--bs-primary);
        color: white;
        border-radius: 50%;
        font-weight: bold;
        cursor: pointer;
        font-size: 1rem;
        transition: all 0.2s ease;
    }
    
    .bib-number:hover {
        background: var(--bs-primary-dark, #0a58ca);
        transform: scale(1.1);
    }
    
    /* Participant status badges */
    .participant-status-badge {
        font-size: 0.8rem;
        padding: 4px 8px;
    }
    
    /* Enhanced scrollable areas */
    .scrollable-area {
        scrollbar-width: thin;
        scrollbar-color: #dee2e6 transparent;
    }
    
    .scrollable-area::-webkit-scrollbar {
        width: 8px;
    }
    
    .scrollable-area::-webkit-scrollbar-track {
        background: transparent;
    }
    
    .scrollable-area::-webkit-scrollbar-thumb {
        background: #dee2e6;
        border-radius: 4px;
    }
    
    .scrollable-area::-webkit-scrollbar-thumb:hover {
        background: #adb5bd;
    }
    
    /* Participant list highlighting */
    .participant-row.on-start {
        background-color: rgba(255, 193, 7, 0.2) !important;
        border-left: 4px solid var(--bs-warning);
    }
    
    .participant-row.latest-run {
        background-color: rgba(25, 135, 84, 0.2) !important;
        border-left: 4px solid var(--bs-success);
    }
    
    /* BIB number styling */
    .bib-number {
        display: inline-flex;
        align-items: center;
        justify-content: center;
        width: 32px;
        height: 32px;
        background: var(--bs-primary);
        color: white;
        border-radius: 50%;
        font-weight: bold;
        cursor: pointer;
        font-size: 0.8rem;
    }
    
    .bib-number:hover {
        background: var(--bs-primary-dark, #0a58ca);
    }
    
    /* Following participants list */
    .following-participant {
        display: flex;
        align-items: center;
        padding: 4px 8px;
        margin-bottom: 2px;
        background: var(--bs-light);
        border-radius: 4px;
        font-size: 0.8rem;
    }
    
    .following-participant .bib {
        background: var(--bs-secondary);
        color: white;
        border-radius: 50%;
        width: 24px;
        height: 24px;
        display: flex;
        align-items: center;
        justify-content: center;
        font-weight: bold;
        font-size: 0.7rem;
        margin-right: 8px;
    }
    
    /* Toast container */
    .toast-container {
        position: fixed;
        top: 20px;
        right: 20px;
        z-index: 9999;
        max-width: 350px;
    }
    
    /* Notification toasts */
    .notification-toast-container {
        z-index: 10000 !important;
    }
    
    .notification-toast {
        min-width: 300px;
        max-width: 400px;
        transition: all 0.3s ease;
        box-shadow: 0 4px 12px rgba(0,0,0,0.3);
    }
    
    .notification-toast:not(.show) {
        opacity: 0;
        transform: translateX(100%);
    }
    
    .notification-toast.show {
        opacity: 1;
        transform: translateX(0);
    }
</style>

<!-- JavaScript -->
<script>
// Heat Management functionality
let heatManagementData = null;
let participantQueue = [];
let queueMode = 'start_list'; // 'start_list' or 'manual'
let autoUpdateInterval = null;
let autoUpdatePaused = false;
let notificationManager = null;
const currentEventId = <?= json_encode($event_id) ?>;
const currentUserId = 'user_' + Date.now(); // You can replace this with actual user ID from session

document.addEventListener('DOMContentLoaded', function() {
    setupEventListeners();
    loadHeatManagementData();
    
    // Initialize notification system
    if (currentEventId) {
        notificationManager = new NotificationManager(currentEventId, currentUserId);
    }
    
    // Start auto-refresh every 15 seconds
    startAutoUpdate();
});

function setupEventListeners() {
    // Control Panel Events
    document.getElementById('activeHeatSelect').addEventListener('change', onHeatSelectionChange);
    document.getElementById('activeRunSelect').addEventListener('change', updateRunOptions);
    document.getElementById('activateHeatBtn').addEventListener('click', activateHeatRun);
    
    // Participant Control Events
    document.getElementById('bibOnStart').addEventListener('input', onBibOnStartChange);
    document.getElementById('setNextFromListBtn').addEventListener('click', setNextFromList);
    document.getElementById('clearLatestBtn').addEventListener('click', clearLatestCompleted);
    document.getElementById('autoNextParticipant').addEventListener('change', toggleAutoAdvance);
    
    // Quick Actions
    document.getElementById('markStartedBtn').addEventListener('click', markParticipantStarted);
    document.getElementById('markCompletedBtn').addEventListener('click', markParticipantCompleted);
    document.getElementById('nextParticipantBtn').addEventListener('click', advanceToNextParticipant);
    document.getElementById('emergencyStopBtn').addEventListener('click', emergencyStop);
    
    // Queue Mode Toggle
    document.querySelectorAll('input[name="queueMode"]').forEach(radio => {
        radio.addEventListener('change', onQueueModeChange);
    });
    
    // Queue refresh
    document.getElementById('refreshQueueBtn').addEventListener('click', refreshParticipantQueue);
    
    // Quick notification buttons
    document.querySelectorAll('.quick-notify-btn').forEach(btn => {
        btn.addEventListener('click', sendQuickNotification);
    });
    
    // Enhanced participant list controls
    if (document.getElementById('filterActiveBtn')) {
        document.getElementById('filterActiveBtn').addEventListener('click', toggleActiveFilter);
    }
    
    // Footer Actions
    document.getElementById('saveHeatSettings').addEventListener('click', saveHeatSettings);
    document.getElementById('deactivateAllBtn').addEventListener('click', deactivateAllHeats);
    document.getElementById('refreshDataBtn').addEventListener('click', loadHeatManagementData);
    document.getElementById('refreshStatusBtn').addEventListener('click', refreshLiveStatus);
    document.getElementById('pauseAutoUpdateBtn').addEventListener('click', toggleAutoUpdate);
    document.getElementById('clearNotificationsBtn').addEventListener('click', clearAllNotifications);
    document.getElementById('toggleParticipantListTrigger').addEventListener('click', toggleParticipantList);
}

async function loadHeatManagementData() {
    if (!currentEventId) {
        showModalError('No event ID provided');
        return;
    }
    
    try {
        const response = await fetch(`heat_management_api.php?action=get_data&event_id=${currentEventId}`);
        const data = await response.json();
        
        if (!response.ok) {
            throw new Error(data.error || 'Failed to load data');
        }
        
        renderHeatManagementData(data);
        
    } catch (error) {
        console.error('Error loading heat management data:', error);
        showModalError(error.message);
    }
}

function renderHeatManagementData(data) {
    document.getElementById('modalLoadingState').style.display = 'none';
    document.getElementById('modalErrorState').style.display = 'none';
    document.getElementById('heatManagementForm').style.display = 'block';
    
    heatManagementData = data;
    
    // Update all UI components
    updateLiveStatus(data.active_heat);
    populateHeatSelect(data.heats);
    updateParticipantQueue(data.active_heat);
    
    if (data.active_heat) {
        document.getElementById('activeHeatSelect').value = data.active_heat.heat_number;
        document.getElementById('activeRunSelect').value = data.active_heat.active_run || 1;
        document.getElementById('bibOnStart').value = data.active_heat.bib_on_start || '';
        document.getElementById('bibLatestRun').value = data.active_heat.bib_latest_on_run || '';
        
        loadParticipants(data.active_heat.heat_number);
    }
}

function updateLiveStatus(activeHeat) {
    const statusGrid = document.getElementById('liveStatusGrid');
    
    if (!activeHeat) {
        statusGrid.innerHTML = `
            <div class="col-12 text-center">
                <div class="alert alert-info mb-0 py-2">
                    <i class="fas fa-info-circle me-2"></i>
                    No heat is currently active
                </div>
            </div>
        `;
        return;
    }
    
    statusGrid.innerHTML = `
        <div class="col-6 col-lg-3">
            <div class="border-0 shadow-none card border-primary h-100">
                <div class="border-0 shadow-none card-body text-center p-2">
                    <i class="fas fa-fire fs-4 mb-1 text-primary"></i>
                    <div class="fw-bold text-primary">Heat ${activeHeat.heat_number}</div>
                    <div class="small text-muted">${activeHeat.heat_name || 'Active Heat'}</div>
                </div>
            </div>
        </div>
        <div class="col-6 col-lg-3">
            <div class="border-0 shadow-none card border-success h-100">
                <div class="border-0 shadow-none card-body text-center p-2">
                    <i class="fas fa-running fs-4 mb-1 text-success"></i>
                    <div class="fw-bold text-success">Run ${activeHeat.active_run}</div>
                    <div class="small text-muted">of ${activeHeat.runs_count}</div>
                </div>
            </div>
        </div>
        <div class="col-6 col-lg-3">
            <div class="border-0 shadow-none card border-warning h-100">
                <div class="border-0 shadow-none card-body text-center p-2">
                    <i class="fas fa-play fs-4 mb-1 text-warning"></i>
                    <div class="fw-bold text-warning">${activeHeat.bib_on_start || '—'}</div>
                    <div class="small text-muted">On Start</div>
                </div>
            </div>
        </div>
        <div class="col-6 col-lg-3">
            <div class="border-0 shadow-none card border-info h-100">
                <div class="border-0 shadow-none card-body text-center p-2">
                    <i class="fas fa-flag-checkered fs-4 mb-1 text-info"></i>
                    <div class="fw-bold text-info">${activeHeat.bib_latest_on_run || '—'}</div>
                    <div class="small text-muted">Latest Run</div>
                </div>
            </div>
        </div>
    `;
}

function populateHeatSelect(heats) {
    const heatSelect = document.getElementById('activeHeatSelect');
    heatSelect.innerHTML = '<option value="">Select Heat</option>';
    
    heats.forEach(heat => {
        const option = document.createElement('option');
        option.value = heat.heat_number;
        option.textContent = `Heat ${heat.heat_number}${heat.heat_name ? ` - ${heat.heat_name}` : ''} (${heat.participant_count} participants)`;
        if (heat.is_active) {
            option.selected = true;
        }
        heatSelect.appendChild(option);
    });
}

async function updateParticipantQueue(activeHeat) {
    if (!activeHeat) {
        clearParticipantQueue();
        return;
    }
    
    try {
        const response = await fetch(`heat_management_api.php?action=get_queue&event_id=${currentEventId}&heat_number=${activeHeat.heat_number}&mode=${queueMode}`);
        const data = await response.json();
        
        if (response.ok) {
            participantQueue = data.queue || [];
            renderParticipantQueue();
        }
    } catch (error) {
        console.error('Error loading participant queue:', error);
    }
}

function renderParticipantQueue() {
    const performingCard = document.getElementById('performingParticipantCard');
    const currentCard = document.getElementById('currentParticipantCard');
    const nextCard = document.getElementById('nextParticipantCard');
    const extendedList = document.getElementById('extendedQueueList');
    
    // Get current form field values (the actual current state)
    const currentPerformingBib = document.getElementById('bibLatestRun').value;
    const currentOnStartBib = document.getElementById('bibOnStart').value;
    
    // Find participants by current form field values instead of API status
    const performingParticipant = currentPerformingBib ? participantQueue.find(p => p.bib_number == currentPerformingBib) : null;
    const onStartParticipant = currentOnStartBib ? participantQueue.find(p => p.bib_number == currentOnStartBib) : null;
    
    // For "NEXT UP", find a participant who is NOT currently performing or on start gate
    const nextParticipant = participantQueue.find(p => 
        p.bib_number != currentPerformingBib && 
        p.bib_number != currentOnStartBib &&
        (p.status === 'next' || p.status === 'waiting')
    );
    
    // Debug logging to help understand the data
    console.log('Participant Queue Debug:', {
        total_participants: participantQueue.length,
        performing_bib: currentPerformingBib,
        performing: performingParticipant ? `BIB ${performingParticipant.bib_number}` : 'none',
        on_start_bib: currentOnStartBib,
        on_start: onStartParticipant ? `BIB ${onStartParticipant.bib_number}` : 'none',
        next: nextParticipant ? `BIB ${nextParticipant.bib_number}` : 'none',
        form_fields: {
            bibLatestRun: currentPerformingBib,
            bibOnStart: currentOnStartBib
        }
    });
    
    // Currently Performing participant
    if (performingParticipant) {
        performingCard.innerHTML = renderParticipantCard(performingParticipant, 'performing');
    } else {
        performingCard.innerHTML = `
            <div class="text-center text-muted py-4">
                <i class="fas fa-running display-4 mb-3 d-block"></i>
                <h6 class="mb-0">No one performing</h6>
                <button class="btn btn-outline-success mt-2" onclick="selectFromQueue('performing')">
                    <i class="fas fa-hand-pointer me-1"></i>Select Performer
                </button>
            </div>
        `;
    }
    
    // On Start Gate participant
    if (onStartParticipant) {
        currentCard.innerHTML = renderParticipantCard(onStartParticipant, 'current');
    } else {
        currentCard.innerHTML = `
            <div class="text-center text-muted py-4">
                <i class="fas fa-user-slash display-4 mb-3 d-block"></i>
                <h6 class="mb-0">No participant on start gate</h6>
                <button class="btn btn-outline-warning mt-2" onclick="selectFromQueue('current')">
                    <i class="fas fa-hand-pointer me-1"></i>Select from Queue
                </button>
            </div>
        `;
    }
    
    // Next participant
    if (nextParticipant) {
        nextCard.innerHTML = renderParticipantCard(nextParticipant, 'next');
    } else {
        nextCard.innerHTML = `
            <div class="text-center text-muted py-4">
                <i class="fas fa-hourglass-half display-4 mb-3 d-block"></i>
                <h6 class="mb-0">No next participant</h6>
                <button class="btn btn-outline-info mt-2" onclick="selectFromQueue('next')">
                    <i class="fas fa-hand-pointer me-1"></i>Select from Queue
                </button>
            </div>
        `;
    }
    
    // Extended queue list (all participants with status indicators)
    if (participantQueue.length > 0) {
        extendedList.innerHTML = participantQueue.map((participant, index) => 
            renderQueueItem(participant, index)
        ).join('');
    } else {
        extendedList.innerHTML = `
            <div class="text-center text-muted py-4">
                <i class="fas fa-list display-4 mb-3 d-block"></i>
                <h6 class="mb-0">No participants in queue</h6>
                <small>Load a heat to see participants</small>
            </div>
        `;
    }
}

function renderQueueItem(participant, index) {
    const position = index + 1;
    let statusClass = '';
    let statusBadge = '';
    let positionIcon = '';
    
    // Determine participant status based on actual queue API status values
    if (participant.status === 'current') {
        statusClass = 'on-start-gate';
        statusBadge = '<span class="badge bg-warning text-dark fs-6"><i class="fas fa-play me-1"></i>ON START GATE</span>';
        positionIcon = '<i class="fas fa-play text-warning fs-4"></i>';
    } else if (participant.status === 'completed') {
        statusClass = 'performing';
        statusBadge = '<span class="badge bg-success fs-6"><i class="fas fa-running me-1"></i>PERFORMING</span>';
        positionIcon = '<i class="fas fa-running text-success fs-4"></i>';
    } else if (participant.status === 'next') {
        statusClass = 'completed';
        statusBadge = '<span class="badge bg-secondary fs-6"><i class="fas fa-flag-checkered me-1"></i>COMPLETED</span>';
        positionIcon = '<i class="fas fa-check text-secondary fs-4"></i>';
    } else if (participant.status === 'next' || index === 1) {
        statusClass = 'next';
        statusBadge = '<span class="badge bg-info fs-6"><i class="fas fa-clock me-1"></i>NEXT UP</span>';
        positionIcon = '<i class="fas fa-clock text-info fs-4"></i>';
    } else {
        statusClass = 'waiting';
        statusBadge = `<span class="badge bg-light text-dark fs-6"><i class="fas fa-hourglass-half me-1"></i>WAITING (#${position})</span>`;
        positionIcon = `<span class="badge bg-light text-dark fs-5">${position}</span>`;
    }
    
    const nameDisplay = `${participant.display_first_name || ''} ${participant.display_last_name || ''}`.trim();
    const categoryDisplay = participant.display_category || 'N/A';
    
    return `
        <div class="queue-participant-item ${statusClass} selectable" data-bib="${participant.bib_number}" onclick="selectParticipantFromQueue(${participant.bib_number})">
            <div class="queue-participant-bib" onclick="event.stopPropagation(); setParticipantOnStart(${participant.bib_number})" title="Click to set as current">
                ${participant.bib_number}
            </div>
            <div class="queue-participant-info">
                <div class="queue-participant-name">${nameDisplay}</div>
                <div class="queue-participant-details">
                    <span class="badge bg-secondary me-1">${categoryDisplay}</span>
                    ${participant.display_country ? `<span class="badge bg-light text-dark me-1">${participant.display_country}</span>` : ''}
                    ${participant.display_club ? `<small class="text-muted d-block mt-1">${participant.display_club}</small>` : ''}
                </div>
            </div>
            <div class="queue-participant-actions">
                <div class="d-flex flex-column align-items-center me-3">
                    ${positionIcon}
                    <small class="mt-2">${statusBadge}</small>
                </div>
                <div class="d-flex flex-column gap-1">
                    <button class="btn btn-warning btn-sm btn-touch" onclick="event.stopPropagation(); setAsOnStartGate(${participant.bib_number})" title="Set as ON START GATE">
                        <i class="fas fa-play me-1"></i>Start Gate
                    </button>
                    <button class="btn btn-success btn-sm btn-touch" onclick="event.stopPropagation(); setAsPerforming(${participant.bib_number})" title="Set as PERFORMING">
                        <i class="fas fa-running me-1"></i>Performing
                    </button>
                </div>
            </div>
        </div>
    `;
}

function renderParticipantCard(participant, type) {
    let statusColor, actionButton1, actionButton2;
    
    switch (type) {
        case 'performing':
            statusColor = 'success';
            actionButton1 = `
                <button class="btn btn-secondary w-100 btn-touch mb-2" onclick="setAsCompleted(${participant.bib_number})">
                    <i class="fas fa-flag-checkered me-1"></i>Mark Completed
                </button>`;
            actionButton2 = `
                <button class="btn btn-outline-warning w-100 btn-touch" onclick="setAsOnStartGate(${participant.bib_number})">
                    <i class="fas fa-step-backward me-1"></i>Back to Start Gate
                </button>`;
            break;
        case 'current':
            statusColor = 'warning';
            actionButton1 = `
                <button class="btn btn-success w-100 btn-touch mb-2" onclick="setAsPerforming(${participant.bib_number})">
                    <i class="fas fa-running me-1"></i>Start Performing
                </button>`;
            actionButton2 = `
                <button class="btn btn-outline-info w-100 btn-touch" onclick="notifyParticipant(${participant.bib_number})">
                    <i class="fas fa-bell me-1"></i>Notify
                </button>`;
            break;
        case 'next':
            statusColor = 'info';
            actionButton1 = `
                <button class="btn btn-warning w-100 btn-touch mb-2" onclick="setAsOnStartGate(${participant.bib_number})">
                    <i class="fas fa-play me-1"></i>Move to Start Gate
                </button>`;
            actionButton2 = `
                <button class="btn btn-outline-info w-100 btn-touch" onclick="notifyParticipant(${participant.bib_number})">
                    <i class="fas fa-bell me-1"></i>Get Ready
                </button>`;
            break;
        default:
            statusColor = 'secondary';
            actionButton1 = `
                <button class="btn btn-warning w-100 btn-touch mb-2" onclick="setAsOnStartGate(${participant.bib_number})">
                    <i class="fas fa-play me-1"></i>Set Start Gate
                </button>`;
            actionButton2 = `
                <button class="btn btn-outline-info w-100 btn-touch" onclick="notifyParticipant(${participant.bib_number})">
                    <i class="fas fa-bell me-1"></i>Notify
                </button>`;
    }
    
    const nameDisplay = `${participant.display_first_name || ''} ${participant.display_last_name || ''}`.trim();
    
    return `
        <div class="participant-card ${type} h-100">
            <div class="d-flex align-items-center mb-3">
                <div class="participant-avatar me-3 bg-${statusColor}">
                    ${participant.bib_number}
                </div>
                <div class="flex-grow-1">
                    <h5 class="mb-1">${nameDisplay}</h5>
                    <div class="d-flex flex-wrap gap-1 mb-1">
                        <span class="badge bg-${statusColor} participant-status-badge">${participant.display_category}</span>
                        ${participant.display_country ? `<span class="badge bg-secondary participant-status-badge">${participant.display_country}</span>` : ''}
                    </div>
                    ${participant.display_club ? `<small class="text-muted">${participant.display_club}</small>` : ''}
                </div>
            </div>
            <div class="d-grid">
                ${actionButton1}
                ${actionButton2}
            </div>
        </div>
    `;
}

// New functions for enhanced functionality
function selectParticipantFromQueue(bibNumber) {
    setParticipantOnStart(bibNumber);
    
    // Scroll to current participant card
    const currentCard = document.getElementById('currentParticipantCard');
    if (currentCard) {
        currentCard.scrollIntoView({ behavior: 'smooth', block: 'center' });
    }
}

function selectFromQueue(position) {
    let message = '';
    switch (position) {
        case 'performing':
            message = '🏃 Select Performer - Choose a participant from the queue below to set as currently performing';
            break;
        case 'current':
            message = '🚪 Select for Start Gate - Choose a participant from the queue below to set on start gate';
            break;
        case 'next':
            message = '⏭️ Select Next Up - Choose a participant from the queue below to set as next up';
            break;
        default:
            message = `📋 Select Participant - Choose a participant from the queue below to set as ${position}`;
    }
    
    showInfoToast('📋 Select Participant', message);
    
    // Highlight the queue list
    const extendedList = document.getElementById('extendedQueueList');
    if (extendedList) {
        extendedList.style.border = '3px solid var(--bs-primary)';
        extendedList.style.borderRadius = '8px';
        
        setTimeout(() => {
            extendedList.style.border = '';
            extendedList.style.borderRadius = '';
        }, 3000);
    }
}

async function refreshParticipantQueue() {
    if (heatManagementData && heatManagementData.active_heat) {
        showInfoToast('🔄 Refreshing Queue', 'Loading latest participant order...');
        await updateParticipantQueue(heatManagementData.active_heat);
        showSuccessToast('✅ Queue Refreshed', 'Participant queue updated successfully');
    } else {
        showErrorToast('❌ No Active Heat', 'Please select and activate a heat first');
    }
}

async function sendQuickNotification(event) {
    const button = event.currentTarget;
    const notificationType = button.getAttribute('data-type');
    
    button.disabled = true;
    button.innerHTML = '<i class="fas fa-spinner fa-spin"></i><br><strong>Sending...</strong>';
    
    try {
        let message = '';
        let title = '';
        
        switch (notificationType) {
            case 'heat_starting':
                const activeHeat = document.getElementById('activeHeatSelect').value;
                const activeRun = document.getElementById('activeRunSelect').value;
                title = '🔥 Heat Starting';
                message = `Heat ${activeHeat}, Run ${activeRun} is about to start. Participants please prepare.`;
                break;
                
            case 'participant_ready':
                const nextBib = document.getElementById('bibOnStart').value;
                const nextParticipant = participantQueue.find(p => p.bib_number == nextBib);
                const nextName = nextParticipant ? `${nextParticipant.display_first_name} ${nextParticipant.display_last_name}` : `Participant #${nextBib}`;
                title = '🏃 Get Ready';
                message = `${nextName} (Bib #${nextBib}), please get ready. You're up next!`;
                break;
                
            case 'scores_ready':
                title = '📊 Scores Ready';
                message = 'Latest scores are now available. Check the scoreboard for results.';
                break;
                
            case 'delay':
                title = '⏳ Competition Delayed';
                message = 'Competition is temporarily delayed. Please stand by for further updates.';
                break;
                
            case 'break':
                title = '☕ Break Time';
                message = 'Taking a short break. Competition will resume shortly.';
                break;
                
            case 'custom':
                const customMessage = prompt('Enter custom notification message:');
                if (!customMessage) {
                    button.disabled = false;
                    restoreButtonText(button, notificationType);
                    return;
                }
                title = '📢 Announcement';
                message = customMessage;
                break;
        }
        
        // Send notification through notification manager
        if (notificationManager && message) {
            await notificationManager.sendCustomNotification(title, message);
            showSuccessToast('📢 Notification Sent', `"${title}" sent to all users`);
        }
        
    } catch (error) {
        console.error('Error sending notification:', error);
        showErrorToast('❌ Send Failed', 'Error: ' + error.message);
    } finally {
        button.disabled = false;
        restoreButtonText(button, notificationType);
    }
}

function restoreButtonText(button, type) {
    const buttonTexts = {
        'heat_starting': '<i class="fas fa-fire display-6 d-block mb-2"></i><strong>Heat Starting</strong><small class="d-block">Notify heat is about to start</small>',
        'participant_ready': '<i class="fas fa-user-check display-6 d-block mb-2"></i><strong>Get Ready</strong><small class="d-block">Next participant prepare</small>',
        'scores_ready': '<i class="fas fa-clipboard-check display-6 d-block mb-2"></i><strong>Scores Ready</strong><small class="d-block">Results available</small>',
        'delay': '<i class="fas fa-pause-circle display-6 d-block mb-2"></i><strong>Delay</strong><small class="d-block">Competition delayed</small>',
        'break': '<i class="fas fa-coffee display-6 d-block mb-2"></i><strong>Break</strong><small class="d-block">Taking a break</small>',
        'custom': '<i class="fas fa-edit display-6 d-block mb-2"></i><strong>Custom</strong><small class="d-block">Send custom message</small>'
    };
    
    button.innerHTML = buttonTexts[type] || button.innerHTML;
}

// Enhanced status management functions
async function setAsOnStartGate(bibNumber) {
    console.log('setAsOnStartGate called with BIB:', bibNumber);
    try {
        // Set participant on start gate (don't clear the current performer)
        document.getElementById('bibOnStart').value = bibNumber;
        onBibOnStartChange();
        
        // Immediately update visual representation
        renderParticipantQueue();
        
        const participant = participantQueue.find(p => p.bib_number == bibNumber);
        const participantName = participant ? `${participant.display_first_name} ${participant.display_last_name}` : `Participant #${bibNumber}`;
        
        console.log('Setting participant on start gate:', participantName);
        
        // Send notification
        if (notificationManager) {
            await notificationManager.notifyParticipantOnStartGate(bibNumber, participantName);
        }
        
        showSuccessToast('🚪 On Start Gate', `${participantName} (Bib #${bibNumber}) is now on the start gate`);
        
        // Save the updated form values to heat settings
        console.log('Calling saveHeatSettings...');
        await saveHeatSettings();
        
    } catch (error) {
        showErrorToast('❌ Update Failed', 'Error: ' + error.message);
    }
}

async function setAsPerforming(bibNumber) {
    console.log('setAsPerforming called with BIB:', bibNumber);
    try {
        // First verify this participant is currently on start gate
        const currentOnStart = document.getElementById('bibOnStart').value;
        if (currentOnStart != bibNumber) {
            showErrorToast('❌ Not on Start Gate', `Participant #${bibNumber} is not currently on start gate`);
            return;
        }
        
        // Check if someone is already performing
        const currentPerforming = document.getElementById('bibLatestRun').value;
        if (currentPerforming) {
            showErrorToast('❌ Someone Already Performing', `Participant #${currentPerforming} is already performing. Mark them as completed first.`);
            return;
        }
        
        // Use the same pattern as the working "Next" button:
        // 1. Update form fields - move from start gate to performing
        document.getElementById('bibLatestRun').value = bibNumber;  // Set as performing
        document.getElementById('bibOnStart').value = '';  // Clear start gate
        
        // 2. Trigger change handler
        onBibOnStartChange();
        
        // Immediately update visual representation
        renderParticipantQueue();
        
        const participant = participantQueue.find(p => p.bib_number == bibNumber);
        const participantName = participant ? `${participant.display_first_name} ${participant.display_last_name}` : `Participant #${bibNumber}`;
        
        console.log('Setting participant as performing:', participantName);
        
        // Send notification
        if (notificationManager) {
            await notificationManager.notifyParticipantPerforming(bibNumber, participantName);
        }
        
        showSuccessToast('🏃 Now Performing', `${participantName} (Bib #${bibNumber}) is now performing`);
        
        // 3. Save heat settings (like the Next button)
        await saveHeatSettings();
        
    } catch (error) {
        showErrorToast('❌ Update Failed', 'Error: ' + error.message);
    }
}

// Enhanced participant list rendering
async function renderAllParticipants(participants) {
    const grid = document.getElementById('allParticipantsGrid');
    
    if (!participants || participants.length === 0) {
        grid.innerHTML = `
            <div class="col-12 text-center py-4">
                <i class="fas fa-users display-4 mb-3 text-muted d-block"></i>
                <h6 class="mb-0">No participants found</h6>
                <small class="text-muted">Load a heat to see participants</small>
            </div>
        `;
        return;
    }
    
    grid.innerHTML = '';
    
    participants.forEach(participant => {
        const card = document.createElement('div');
        card.className = 'col-lg-4 col-md-6';
        
        let statusClass = '';
        let statusBadge = '';
        let actionButtons = '';
        
        // Determine status styling
        switch (participant.status) {
            case 'on_start_gate':
                statusClass = 'on-start-gate';
                statusBadge = '<span class="badge bg-warning text-dark fs-6"><i class="fas fa-play me-1"></i>ON START GATE</span>';
                actionButtons = `
                    <button class="btn btn-success btn-sm me-1" onclick="setAsPerforming(${participant.bib_number})">
                        <i class="fas fa-running me-1"></i>Set Performing
                    </button>
                `;
                break;
            case 'performing':
                statusClass = 'performing';
                statusBadge = '<span class="badge bg-success fs-6"><i class="fas fa-running me-1"></i>PERFORMING</span>';
                actionButtons = `
                    <button class="btn btn-secondary btn-sm me-1" onclick="setAsCompleted(${participant.bib_number})">
                        <i class="fas fa-flag-checkered me-1"></i>Complete
                    </button>
                `;
                break;
            case 'completed':
                statusClass = 'completed';
                statusBadge = '<span class="badge bg-secondary fs-6"><i class="fas fa-check me-1"></i>COMPLETED</span>';
                actionButtons = `
                    <button class="btn btn-warning btn-sm me-1" onclick="setAsOnStartGate(${participant.bib_number})">
                        <i class="fas fa-redo me-1"></i>Reset
                    </button>
                `;
                break;
            default:
                statusBadge = '<span class="badge bg-info fs-6"><i class="fas fa-clock me-1"></i>WAITING</span>';
                actionButtons = `
                    <button class="btn btn-warning btn-sm me-1" onclick="setAsOnStartGate(${participant.bib_number})">
                        <i class="fas fa-play me-1"></i>Start Gate
                    </button>
                `;
        }
        
        const nameDisplay = `${participant.display_first_name || ''} ${participant.display_last_name || ''}`.trim();
        const categoryDisplay = participant.display_category || 'N/A';
        
        card.innerHTML = `
            <div class="card h-100 queue-participant-item ${statusClass}" style="cursor: default;">
                <div class="card-body p-3">
                    <div class="d-flex align-items-start mb-3">
                        <div class="queue-participant-bib me-3" onclick="setAsOnStartGate(${participant.bib_number})" style="cursor: pointer;">
                            ${participant.bib_number}
                        </div>
                        <div class="flex-grow-1">
                            <h6 class="mb-1">${nameDisplay}</h6>
                            <div class="d-flex flex-wrap gap-1 mb-2">
                                <span class="badge bg-secondary">${categoryDisplay}</span>
                                ${participant.display_country ? `<span class="badge bg-light text-dark">${participant.display_country}</span>` : ''}
                            </div>
                            ${participant.display_club ? `<small class="text-muted">${participant.display_club}</small>` : ''}
                        </div>
                    </div>
                    
                    <div class="mb-3">
                        ${statusBadge}
                    </div>
                    
                    <div class="d-flex gap-1 flex-wrap">
                        ${actionButtons}
                        <button class="btn btn-outline-primary btn-sm" onclick="notifyParticipant(${participant.bib_number})">
                            <i class="fas fa-bell me-1"></i>Notify
                        </button>
                    </div>
                </div>
            </div>
        `;
        
        grid.appendChild(card);
    });
}

async function setAsCompleted(bibNumber) {
    try {
        // Check if this participant is currently performing
        const currentPerforming = document.getElementById('bibLatestRun').value;
        if (currentPerforming != bibNumber) {
            showErrorToast('❌ Not Currently Performing', `Participant #${bibNumber} is not currently performing`);
            return;
        }
        
        // Mark participant as completed - remove them from performing
        document.getElementById('bibLatestRun').value = '';  // Clear performing box
        
        onBibOnStartChange();
        
        // Immediately update visual representation
        renderParticipantQueue();
        
        const participant = participantQueue.find(p => p.bib_number == bibNumber);
        const participantName = participant ? `${participant.display_first_name} ${participant.display_last_name}` : `Participant #${bibNumber}`;
        
        // Send notification
        if (notificationManager) {
            await notificationManager.notifyParticipantCompleted(bibNumber, participantName);
        }
        
        showSuccessToast('🏁 Completed', `${participantName} (Bib #${bibNumber}) has completed and removed from performing`);
        
        // Save the updated form values to heat settings
        await saveHeatSettings();
        
    } catch (error) {
        showErrorToast('❌ Update Failed', 'Error: ' + error.message);
    }
}

// Enhanced participant list management
let showActiveOnly = false;

function toggleActiveFilter() {
    showActiveOnly = !showActiveOnly;
    const btn = document.getElementById('filterActiveBtn');
    
    if (showActiveOnly) {
        btn.innerHTML = '<i class="fas fa-users me-1"></i>Show All';
        btn.className = 'btn btn-primary btn-sm';
    } else {
        btn.innerHTML = '<i class="fas fa-filter me-1"></i>Show Active Only';
        btn.className = 'btn btn-outline-primary btn-sm';
    }
    
    // Reload participants with filter
    if (heatManagementData && heatManagementData.active_heat) {
        loadAllParticipants(heatManagementData.active_heat.heat_number);
    }
}

async function loadAllParticipants(heatNumber) {
    try {
        // Use the existing get_participants endpoint
        const response = await fetch(`heat_management_api.php?action=get_participants&event_id=${currentEventId}&heat_number=${heatNumber}`);
        const data = await response.json();
        
        if (!response.ok) {
            throw new Error(data.error || 'Failed to load participants');
        }
        
        let participants = data.participants || [];
        
        // Apply filter if needed
        if (showActiveOnly) {
            participants = participants.filter(p => 
                ['on_start', 'latest_run'].includes(p.status)
            );
        }
        
        renderAllParticipants(participants);
        
    } catch (error) {
        console.error('Error loading all participants:', error);
        const grid = document.getElementById('allParticipantsGrid');
        grid.innerHTML = `
            <div class="col-12 text-center py-4">
                <div class="alert alert-danger">
                    <i class="fas fa-exclamation-triangle me-2"></i>
                    Error loading participants: ${error.message}
                </div>
                <button class="btn btn-outline-primary mt-2" onclick="loadAllParticipants(${heatNumber})">
                    <i class="fas fa-redo me-1"></i>Try Again
                </button>
            </div>
        `;
    }
}

function clearParticipantQueue() {
    document.getElementById('performingParticipantCard').innerHTML = `
        <div class="text-center text-muted py-4">
            <i class="fas fa-running display-4 mb-3 d-block"></i>
            <h6 class="mb-0">No active heat</h6>
            <small>Select and activate a heat to see performers</small>
        </div>
    `;
    document.getElementById('currentParticipantCard').innerHTML = `
        <div class="text-center text-muted py-4">
            <i class="fas fa-user-slash display-4 mb-3 d-block"></i>
            <h6 class="mb-0">No active heat</h6>
            <small>Select and activate a heat to see participants</small>
        </div>
    `;
    document.getElementById('nextParticipantCard').innerHTML = `
        <div class="text-center text-muted py-4">
            <i class="fas fa-hourglass-half display-4 mb-3 d-block"></i>
            <h6 class="mb-0">No active heat</h6>
            <small>Select and activate a heat to see participants</small>
        </div>
    `;
    document.getElementById('extendedQueueList').innerHTML = `
        <div class="text-center text-muted py-4">
            <i class="fas fa-list display-4 mb-3 d-block"></i>
            <h6 class="mb-0">No participants available</h6>
            <small>Load a heat to see the participant queue</small>
        </div>
    `;
}

// Quick Action Functions
async function markParticipantStarted() {
    const bibOnStart = document.getElementById('bibOnStart').value;
    if (!bibOnStart) {
        showErrorToast('❌ No participant selected for start', 'Please select a participant first');
        return;
    }
    
    // Find participant name for notification
    const participant = participantQueue.find(p => p.bib_number == bibOnStart);
    const participantName = participant ? `${participant.display_first_name} ${participant.display_last_name}` : `Participant #${bibOnStart}`;
    
    showInfoToast('🔄 Processing...', `Setting participant #${bibOnStart} as started`);
    
    // Send notification to all users
    if (notificationManager) {
        await notificationManager.notifyParticipantStarted(bibOnStart, participantName);
    }
    
    await updateParticipantStatus(bibOnStart, 'started');
}

async function markParticipantCompleted() {
    const bibLatestRun = document.getElementById('bibLatestRun').value;
    if (!bibLatestRun) {
        showErrorToast('❌ No one performing', 'No participant is currently performing to mark as completed');
        return;
    }
    
    // Find participant name for notification
    const participant = participantQueue.find(p => p.bib_number == bibLatestRun);
    const participantName = participant ? `${participant.display_first_name} ${participant.display_last_name}` : `Participant #${bibLatestRun}`;
    
    showInfoToast('🔄 Processing...', `Marking participant #${bibLatestRun} as completed`);
    
    // Send notification to all users
    if (notificationManager) {
        await notificationManager.notifyParticipantCompleted(bibLatestRun, participantName);
    }
    
    // ONLY clear the performing participant - don't move anyone else
    // 1. Clear the "PERFORMING NOW" box
    document.getElementById('bibLatestRun').value = '';
    
    // 2. Trigger change handler
    onBibOnStartChange();
    
    // Immediately update visual representation
    renderParticipantQueue();
    
    // 3. Save heat settings
    await saveHeatSettings();
    
    showSuccessToast('🏁 Completed', `${participantName} (Bib #${bibLatestRun}) has completed and removed from performing`);
}

async function advanceToNextParticipant() {
    const nextParticipant = participantQueue.find(p => p.status === 'next') || participantQueue[1];
    if (nextParticipant) {
        const currentBib = document.getElementById('bibOnStart').value;
        document.getElementById('bibOnStart').value = nextParticipant.bib_number;
        onBibOnStartChange();
        
        const participantName = `${nextParticipant.display_first_name} ${nextParticipant.display_last_name}`;
        
        // Send notification to all users
        if (notificationManager) {
            await notificationManager.notifyAutoAdvance(currentBib, nextParticipant.bib_number, participantName);
        }
        
        showSuccessToast('⏭️ Advanced to Next Participant', `Moved from #${currentBib} to #${nextParticipant.bib_number} (${participantName})`);
        await saveHeatSettings();
    } else {
        showErrorToast('⚠️ No next participant available', 'End of participant queue reached');
    }
}

async function emergencyStop() {
    if (!confirm('🚨 EMERGENCY STOP\n\nAre you sure you want to stop the competition immediately?\n\nThis will deactivate all heats and stop the current competition.')) {
        return;
    }
    
    // Send notification to all users
    if (notificationManager) {
        await notificationManager.notifyEmergencyStop();
    }
    
    showWarningToast('🚨 Emergency Stop Initiated', 'Stopping all competition activities...');
    await deactivateAllHeats();
}

// Event Handlers and Helper Functions
async function activateHeatRun() {
    const selectedHeat = document.getElementById('activeHeatSelect').value;
    const selectedRun = document.getElementById('activeRunSelect').value;
    
    if (!selectedHeat) {
        showErrorToast('❌ Heat Selection Required', 'Please select a heat before activating');
        return;
    }
    
    // Send notification to all users
    if (notificationManager) {
        await notificationManager.notifyHeatActivated(selectedHeat, selectedRun);
    }
    
    showInfoToast('🔄 Activating Heat/Run...', `Setting Heat ${selectedHeat}, Run ${selectedRun} as active`);
    await saveHeatSettings();
}

async function setNextFromList() {
    if (participantQueue.length > 1) {
        const nextParticipant = participantQueue[1];
        const previousBib = document.getElementById('bibOnStart').value;
        document.getElementById('bibOnStart').value = nextParticipant.bib_number;
        onBibOnStartChange();
        
        const participantName = `${nextParticipant.display_first_name} ${nextParticipant.display_last_name}`;
        
        // Send notification to all users
        if (notificationManager) {
            await notificationManager.notifyNextParticipant(nextParticipant.bib_number, participantName);
        }
        
        showSuccessToast('✅ Next Participant Set', `Set #${nextParticipant.bib_number} (${participantName}) from queue`);
    } else {
        showErrorToast('❌ Queue Empty', 'No next participant available in the current queue');
    }
}

async function clearLatestCompleted() {
    const previousValue = document.getElementById('bibLatestRun').value;
    document.getElementById('bibLatestRun').value = '';
    
    // Use the same pattern as other working functions
    onBibOnStartChange();
    await saveHeatSettings();
    
    if (previousValue) {
        showSuccessToast('🗑️ Cleared Latest Completed', `Removed participant #${previousValue} from latest completed`);
    } else {
        showInfoToast('ℹ️ Already Clear', 'Latest completed field was already empty');
    }
}

function toggleAutoAdvance() {
    const autoAdvance = document.getElementById('autoNextParticipant').checked;
    if (autoAdvance) {
        showSuccessToast('⚡ Auto-Advance Enabled', 'Participants will automatically advance when marked as completed');
    } else {
        showInfoToast('⏸️ Auto-Advance Disabled', 'Manual participant progression enabled');
    }
}

async function refreshLiveStatus() {
    showInfoToast('🔄 Refreshing Data...', 'Loading latest competition status');
    await loadHeatManagementData();
    showSuccessToast('✅ Data Refreshed', 'Competition status updated successfully');
}

function startAutoUpdate() {
    if (autoUpdateInterval) {
        clearInterval(autoUpdateInterval);
    }
    
    autoUpdateInterval = setInterval(() => {
        if (!autoUpdatePaused) {
            loadHeatManagementData();
        }
    }, 15000); // 15 seconds
    
    autoUpdatePaused = false;
    updateAutoUpdateButton();
}

function stopAutoUpdate() {
    if (autoUpdateInterval) {
        clearInterval(autoUpdateInterval);
        autoUpdateInterval = null;
    }
    autoUpdatePaused = true;
    updateAutoUpdateButton();
}

function toggleAutoUpdate() {
    if (autoUpdatePaused) {
        startAutoUpdate();
        showSuccessToast('▶️ Auto-Update Resumed', 'Data will refresh automatically every 15 seconds');
    } else {
        stopAutoUpdate();
        showInfoToast('⏸️ Auto-Update Paused', 'Automatic data refresh has been paused');
    }
}

function updateAutoUpdateButton() {
    const btn = document.getElementById('pauseAutoUpdateBtn');
    const statusIndicator = document.getElementById('liveStatusIndicator');
    
    if (autoUpdatePaused) {
        btn.innerHTML = '<i class="fas fa-play"></i>';
        btn.className = 'btn btn-outline-warning btn-sm px-2 py-1';
        statusIndicator.innerHTML = '<i class="fas fa-pause me-1"></i>PAUSED';
        statusIndicator.className = 'badge bg-warning live-paused px-2 py-1';
    } else {
        btn.innerHTML = '<i class="fas fa-pause"></i>';
        btn.className = 'btn btn-outline-primary btn-sm px-2 py-1';
        statusIndicator.innerHTML = '<i class="fas fa-circle me-1"></i>LIVE';
        statusIndicator.className = 'badge bg-success live-pulse px-2 py-1';
    }
}

async function updateParticipantStatus(bibNumber, status) {
    const formData = new FormData();
    formData.append('action', 'update_participant_status');
    formData.append('event_id', currentEventId);
    formData.append('bib_number', bibNumber);
    formData.append('status', status);
    
    try {
        const response = await fetch('heat_management_api.php', {
            method: 'POST',
            body: formData
        });
        
        const data = await response.json();
        
        if (!response.ok) {
            throw new Error(data.error || 'Failed to update participant status');
        }
        
        const statusIcons = {
            'started': '🏁',
            'completed': '🏆',
            'waiting': '⏳'
        };
        
        const statusText = {
            'started': 'Started',
            'completed': 'Completed',
            'waiting': 'Waiting'
        };
        
        showSuccessToast(
            `${statusIcons[status]} Participant ${statusText[status]}`, 
            `Participant #${bibNumber} has been marked as ${statusText[status].toLowerCase()}`
        );
        
        loadHeatManagementData(); // Refresh data
        
    } catch (error) {
        console.error('Error updating participant status:', error);
        showErrorToast('❌ Update Failed', 'Error: ' + error.message);
    }
}

async function loadParticipants(heatNumber) {
    try {
        const response = await fetch(`heat_management_api.php?action=get_participants&event_id=${currentEventId}&heat_number=${heatNumber}`);
        const data = await response.json();
        
        if (!response.ok) {
            throw new Error(data.error || 'Failed to load participants');
        }
        
        renderAllParticipants(data.participants || []);
        
    } catch (error) {
        console.error('Error loading participants:', error);
        const grid = document.getElementById('allParticipantsGrid');
        if (grid) {
            grid.innerHTML = `
                <div class="col-12 text-center py-4">
                    <div class="alert alert-danger">
                        <i class="fas fa-exclamation-triangle me-2"></i>
                        Error loading participants: ${error.message}
                    </div>
                </div>
            `;
        }
    }
}

function renderParticipants(participants) {
    const tableBody = document.getElementById('participantsTableBody');
    
    // If the table doesn't exist, fall back to grid rendering
    if (!tableBody) {
        console.warn('participantsTableBody not found, using grid rendering instead');
        renderAllParticipants(participants);
        return;
    }
    
    if (participants.length === 0) {
        tableBody.innerHTML = `
            <tr><td colspan="5" class="text-center text-muted">No participants found</td></tr>
        `;
        return;
    }
    
    tableBody.innerHTML = '';
    
    participants.forEach(participant => {
        const row = document.createElement('tr');
        row.className = 'participant-row';
        
        let statusBadge = '';
        let statusClass = '';
        
        switch (participant.status) {
            case 'on_start':
                statusBadge = '<span class="badge bg-warning"><i class="fas fa-play me-1"></i>On Start</span>';
                statusClass = 'on-start';
                break;
            case 'latest_run':
                statusBadge = '<span class="badge bg-success"><i class="fas fa-flag-checkered me-1"></i>Latest Run</span>';
                statusClass = 'latest-run';
                break;
            case 'completed':
                statusBadge = '<span class="badge bg-secondary"><i class="fas fa-check me-1"></i>Completed</span>';
                statusClass = 'completed';
                break;
            default:
                statusBadge = '<span class="badge bg-info"><i class="fas fa-clock me-1"></i>Waiting</span>';
        }
        
        row.className += ` ${statusClass}`;
        
        const nameDisplay = `${participant.display_first_name || ''} ${participant.display_last_name || ''}`.trim();
        const categoryDisplay = participant.display_category || 'N/A';
        
        row.innerHTML = `
            <td>
                <span class="bib-number" data-bib="${participant.bib_number}">
                    ${participant.bib_number}
                </span>
            </td>
            <td>${nameDisplay}</td>
            <td>
                <span class="badge bg-secondary">${categoryDisplay}</span>
            </td>
            <td>${statusBadge}</td>
            <td>
                <button type="button" class="btn btn-sm btn-outline-primary" onclick="setParticipantOnStart(${participant.bib_number})">
                    <i class="fas fa-play me-1"></i>Set On Start
                </button>
            </td>
        `;
        
        tableBody.appendChild(row);
    });
}

async function deactivateAllHeats() {
    if (!confirm('🛑 STOP ALL COMPETITION ACTIVITIES\n\nThis will:\n• Deactivate all heats\n• Clear all participant positions\n• Stop the current competition\n\nAre you sure you want to continue?')) {
        return;
    }
    
    const formData = new FormData();
    formData.append('action', 'deactivate_all');
    formData.append('event_id', currentEventId);
    
    try {
        showWarningToast('🛑 Stopping Competition...', 'Deactivating all heats and clearing positions');
        
        const response = await fetch('heat_management_api.php', {
            method: 'POST',
            body: formData
        });
        
        const data = await response.json();
        
        if (!response.ok) {
            throw new Error(data.error || 'Failed to deactivate heats');
        }
        
        showSuccessToast('🛑 Competition Stopped', 'All heats have been deactivated and competition stopped');
        loadHeatManagementData();
        
        window.dispatchEvent(new CustomEvent('heatSettingsUpdated', { detail: data }));
        
    } catch (error) {
        console.error('Error deactivating heats:', error);
        showErrorToast('❌ Stop Failed', 'Error: ' + error.message);
    }
}

function updateRunOptions(runsCount = 1) {
    const runSelect = document.getElementById('activeRunSelect');
    const selectedHeat = document.getElementById('activeHeatSelect').value;
    
    if (selectedHeat && heatManagementData) {
        const heatData = heatManagementData.heats.find(h => h.heat_number == selectedHeat);
        runsCount = heatData ? heatData.runs_count : 1;
    }
    
    const currentValue = runSelect.value;
    runSelect.innerHTML = '';
    
    for (let i = 1; i <= runsCount; i++) {
        const option = document.createElement('option');
        option.value = i;
        option.textContent = `Run ${i}`;
        runSelect.appendChild(option);
    }
    
    // Restore previous selection if valid
    if (currentValue <= runsCount) {
        runSelect.value = currentValue;
    }
}

function onHeatSelectionChange() {
    const selectedHeat = document.getElementById('activeHeatSelect').value;
    
    if (selectedHeat && heatManagementData) {
        const heatData = heatManagementData.heats.find(h => h.heat_number == selectedHeat);
        if (heatData) {
            updateRunOptions(heatData.runs_count);
            updateParticipantQueue(heatData);
        }
    }
}

function onQueueModeChange(event) {
    queueMode = event.target.value;
    if (heatManagementData && heatManagementData.active_heat) {
        updateParticipantQueue(heatManagementData.active_heat);
    }
}

function onBibOnStartChange() {
    const bibValue = document.getElementById('bibOnStart').value;
    
    // Update visual indicators
    document.querySelectorAll('.participant-row').forEach(row => {
        row.classList.remove('on-start');
        const bib = row.querySelector('.bib-number');
        if (bib && bib.textContent.trim() == bibValue) {
            row.classList.add('on-start');
        }
    });
}

function setParticipantOnStart(bibNumber) {
    const previousBib = document.getElementById('bibOnStart').value;
    document.getElementById('bibOnStart').value = bibNumber;
    onBibOnStartChange();
    
    // Send notification to all users if participant changed
    if (previousBib != bibNumber && notificationManager) {
        const participant = participantQueue.find(p => p.bib_number == bibNumber);
        const participantName = participant ? `${participant.display_first_name} ${participant.display_last_name}` : `Participant #${bibNumber}`;
        notificationManager.notifyParticipantOnStart(bibNumber, participantName);
    }
}

function toggleParticipantList() {
    const section = document.getElementById('participantListSection');
    const trigger = document.getElementById('toggleParticipantListTrigger');
    
    if (section.style.display === 'none' || section.style.display === '') {
        section.style.display = 'block';
        trigger.innerHTML = '<i class="fas fa-eye-slash me-1"></i>Hide All Participants';
        
        // Load all participants with enhanced styling if not already loaded
        if (heatManagementData && heatManagementData.active_heat) {
            loadAllParticipants(heatManagementData.active_heat.heat_number);
        }
    } else {
        section.style.display = 'none';
        trigger.innerHTML = '<i class="fas fa-table me-1"></i>Show All Participants';
    }
}

async function notifyParticipant(bibNumber) {
    const participant = participantQueue.find(p => p.bib_number == bibNumber);
    if (!participant) {
        showErrorToast('❌ Participant Not Found', `Cannot find participant with BIB #${bibNumber}`);
        return;
    }
    
    const participantName = `${participant.display_first_name} ${participant.display_last_name}`;
    const message = `${participantName} (Bib #${bibNumber}), please check in with competition officials.`;
    
    try {
        if (notificationManager) {
            await notificationManager.sendCustomNotification('📢 Participant Call', message);
            showSuccessToast('📢 Participant Notified', `Called ${participantName} (Bib #${bibNumber})`);
        }
    } catch (error) {
        showErrorToast('❌ Notification Failed', 'Error: ' + error.message);
    }
}

// Keep all the existing utility functions but update UI calls
async function saveHeatSettings() {
    const formData = new FormData();
    
    formData.append('action', 'update_settings');
    formData.append('event_id', currentEventId);
    formData.append('active_heat', document.getElementById('activeHeatSelect').value);
    formData.append('active_run', document.getElementById('activeRunSelect').value);
    formData.append('bib_on_start', document.getElementById('bibOnStart').value);
    formData.append('bib_latest_on_run', document.getElementById('bibLatestRun').value);
    
    try {
        const saveBtn = document.getElementById('saveHeatSettings');
        saveBtn.disabled = true;
        saveBtn.innerHTML = '<i class="fas fa-spinner fa-spin me-1"></i>Applying Changes...';
        
        showInfoToast('💾 Saving Settings...', 'Applying competition configuration changes');
        
        const response = await fetch('heat_management_api.php', {
            method: 'POST',
            body: formData
        });
        
        const data = await response.json();
        
        if (!response.ok) {
            throw new Error(data.error || 'Failed to save settings');
        }
        
        showSuccessToast('✅ Settings Applied Successfully', data.message || 'Competition configuration updated');
        loadHeatManagementData(); // Refresh all data
        
        window.dispatchEvent(new CustomEvent('heatSettingsUpdated', { detail: data }));
        
    } catch (error) {
        console.error('Error saving settings:', error);
        showErrorToast('❌ Save Failed', 'Error: ' + error.message);
    } finally {
        const saveBtn = document.getElementById('saveHeatSettings');
        saveBtn.disabled = false;
        saveBtn.innerHTML = '<i class="fas fa-broadcast-tower me-1"></i>Apply All Changes';
    }
}

// Utility functions for UI updates
function showModalLoading() {
    document.getElementById('modalLoadingState').style.display = 'block';
    document.getElementById('modalErrorState').style.display = 'none';
    document.getElementById('heatManagementForm').style.display = 'none';
}

function showModalError(message) {
    document.getElementById('modalLoadingState').style.display = 'none';
    document.getElementById('modalErrorState').style.display = 'block';
    document.getElementById('heatManagementForm').style.display = 'none';
    document.getElementById('modalErrorMessage').textContent = message;
}

function showSuccessToast(title, message = '') {
    createToast(title, message, 'success');
}

function showErrorToast(title, message = '') {
    createToast(title, message, 'danger');
}

function showWarningToast(title, message = '') {
    createToast(title, message, 'warning');
}

function showInfoToast(title, message = '') {
    createToast(title, message, 'info');
}

function createToast(title, message, type) {
    // Create toast container if it doesn't exist
    let container = document.querySelector('.toast-container');
    if (!container) {
        container = document.createElement('div');
        container.className = 'toast-container';
        document.body.appendChild(container);
    }
    
    const toast = document.createElement('div');
    toast.className = `toast command-toast align-items-center text-white bg-${type} border-0`;
    toast.setAttribute('role', 'alert');
    toast.setAttribute('aria-live', 'assertive');
    toast.setAttribute('aria-atomic', 'true');
    
    const toastId = 'toast_' + Date.now();
    toast.id = toastId;
    
    const iconMap = {
        'success': 'fa-check-circle',
        'danger': 'fa-exclamation-circle',
        'warning': 'fa-exclamation-triangle',
        'info': 'fa-info-circle'
    };
    
    toast.innerHTML = `
        <div class="toast-header bg-transparent text-white border-0">
            <i class="fas ${iconMap[type]} me-2"></i>
            <strong class="me-auto">${title}</strong>
            <small class="opacity-75">${new Date().toLocaleTimeString()}</small>
            <button type="button" class="btn-close btn-close-white ms-2" data-bs-dismiss="toast" aria-label="Close"></button>
        </div>
        ${message ? `<div class="toast-body border-top border-light border-opacity-25">${message}</div>` : ''}
    `;
    
    container.appendChild(toast);
    
    // Auto-remove after 20 seconds
    setTimeout(() => {
        if (document.body.contains(toast)) {
            toast.style.opacity = '0';
            toast.style.transform = 'translateX(100%)';
            setTimeout(() => {
                if (container.contains(toast)) {
                    container.removeChild(toast);
                }
            }, 300);
        }
    }, 20000); // 20 seconds
    
    // Add click handler for manual close
    const closeBtn = toast.querySelector('.btn-close');
    if (closeBtn) {
        closeBtn.addEventListener('click', () => {
            toast.style.opacity = '0';
            toast.style.transform = 'translateX(100%)';
            setTimeout(() => {
                if (container.contains(toast)) {
                    container.removeChild(toast);
                }
            }, 300);
        });
    }
    
    // Animate in
    toast.style.opacity = '0';
    toast.style.transform = 'translateX(100%)';
    toast.style.transition = 'all 0.3s ease';
    
    setTimeout(() => {
        toast.style.opacity = '1';
        toast.style.transform = 'translateX(0)';
    }, 10);
}

// Expose functions globally
window.HeatManagement = {
    loadData: loadHeatManagementData,
    saveSettings: saveHeatSettings,
    setParticipantOnStart: setParticipantOnStart,
    getData: () => heatManagementData,
    getNotificationManager: () => notificationManager
};

// Clear all notifications function
async function clearAllNotifications() {
    if (!confirm('🧹 Clear All Notifications\n\nThis will remove all notifications for all users in this event.\n\nAre you sure you want to continue?')) {
        return;
    }
    
    try {
        if (notificationManager) {
            await notificationManager.clearAllNotifications();
            showSuccessToast('🧹 Notifications Cleared', 'All event notifications have been removed');
        }
    } catch (error) {
        showErrorToast('❌ Clear Failed', 'Error: ' + error.message);
    }
}
</script>

<?php if ($standalone): ?>
        </div>
    </div>

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