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

$selected_event_id = $_GET['event_id'] ?? '';
$event_data = null;

// Load basic event info for the header
if ($selected_event_id) {
    $event_stmt = $pdo->prepare("SELECT id, name, heats_total, date FROM events WHERE id = ?");
    $event_stmt->execute([$selected_event_id]);
    $event_data = $event_stmt->fetch(PDO::FETCH_ASSOC);
}
?>

<!DOCTYPE html>
<html>
<head>
    <title>Heat Flow Preview</title>
    <!-- style skin holder -->
    <?php include_once '../includes/stylesheets.php'; ?>
</head>
<body class="body-bg-aurora-bright">
    <?php include '../menu.php'; ?>
    
    <!-- Test the notification system -->
    <div class="position-fixed" style="top: 80px; right: 20px; z-index: 9995;">
        <div class="btn-group-vertical">
            <button class="btn btn-success btn-sm mb-1" onclick="testNotificationSystem()" title="Test Basic Notifications">
                <i class="fas fa-bell"></i> Test
            </button>
            <button class="btn btn-warning btn-sm mb-1" onclick="testHeatNotifications()" title="Test Heat Notifications">
                <i class="fas fa-fire"></i> Heat
            </button>
            <button class="btn btn-info btn-sm mb-1" onclick="testParticipantNotifications()" title="Test Participant Notifications">
                <i class="fas fa-user"></i> Part.
            </button>
            <button class="btn btn-danger btn-sm mb-1" onclick="testEmergencyStop()" title="Test Emergency Stop">
                <i class="fas fa-stop"></i> STOP
            </button>
            <button class="btn btn-secondary btn-sm" onclick="debugNotificationSystem()" title="Debug Notification System">
                <i class="fas fa-bug"></i> Debug
            </button>
        </div>
    </div>
    <div class="container-fluid container-StyleScore p-4">
            <!-- event action menu. -->
<div class="row mb-2">
    <div class="col-12">
        <?php       
        $use_localStorage = true;
        $show_header = false;
        //$show_public_view = false;
        include 'event_actions_menu.php'; 
        ?>
    </div>
</div>
         <div class="row justify-content-center">
            <div class="col-12">
                <!-- Event Header -->
                <div class="border-0 shadow-none card mb-3">
                    <div class="border-0 shadow-none card-body p-3">
                    <?php if ($event_data): ?>
                        <h4 class="mb-2">
                            <i class="fas fa-fire me-2"></i>
                            <?= htmlspecialchars($event_data['name']) ?>
                        </h4>
                        <div class="d-flex justify-content-between align-items-center flex-wrap gap-2">
                            <span class="text-muted small">Heat Flow Preview • <?= $event_data['heats_total'] ?> Heats</span>
                            <div class="d-inline-flex align-items-center gap-2">
                                <i class="fas fa-sync-alt"></i>
                                <span class="small">Auto-update:</span>
                                <select class="form-select form-select-sm w-auto" id="updateInterval">
                                    <option value="0">Off</option>
                                    <option value="5">5s</option>
                                    <option value="10">10s</option>
                                    <option value="30" selected>30s</option>
                                </select>
                                <small class="text-muted" id="countdownTimer"></small>
                            </div>
                            <div class="d-inline-flex align-items-center gap-2 ms-auto">
                                <span class="badge bg-success rounded-pill p-1"></span>
                                <span class="text-muted small">Live Updates</span>
                            </div>
                        </div>
                    <?php else: ?>
                        <h4 class="mb-2">
                            <i class="fas fa-exclamation-triangle me-2"></i>
                            Event Not Found
                        </h4>
                        <p class="text-muted mb-0">Please check the event ID and try again</p>
                    <?php endif; ?>
                    </div>
                </div>

                <!-- Main Content -->
                <div>
                    <?php if ($event_data): ?>
                    <!-- Loading State -->
                    <div id="loading-state" 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 heat flow data...</p>
                        </div>

                        <!-- Error State -->
                        <div id="error-state" class="alert alert-danger text-center d-none">
                            <div class="mb-2">
                                <i class="fas fa-exclamation-circle fa-lg"></i>
                            </div>
                            <h6 class="mb-2">Failed to Load Data</h6>
                            <p id="error-message" class="mb-2 small">An error occurred while loading the heat flow data.</p>
                            <button class="btn btn-outline-danger btn-sm" onclick="loadFlowData()">
                                <i class="fas fa-redo me-1"></i>Try Again
                            </button>
                        </div>

                        <!-- Empty State -->
                        <div id="empty-state" class="alert alert-info text-center d-none">
                            <div class="mb-2">
                                <i class="fas fa-inbox fa-lg"></i>
                            </div>
                            <h6 class="mb-2">No Heat Configuration Found</h6>
                            <p class="mb-2 small">This event doesn't have any heat configurations yet.</p>
                            <a href="admin_heat_config.php?event_id=<?= $selected_event_id ?>" class="btn btn-outline-primary btn-sm">
                                <i class="fas fa-cogs me-1"></i>Configure Heats
                            </a>
                        </div>
                        <!-- General Reports (event-level) -->
                        <div id="general-reports-card" class="card mb-2 d-none">
                            <div class="border-0 shadow-none card-header d-flex justify-content-between align-items-center py-2">
                                <small class="text-uppercase fw-bold"><i class="fas fa-folder-open me-1"></i>General Reports</small>
                                <button class="btn btn-sm btn-outline-secondary" onclick="refreshGeneralReports(eventId)">
                                    <i class="fas fa-sync-alt"></i>
                                </button>
                            </div>
                            <div class="border-0 shadow-none card-body py-2">
                                <div id="general-reports" class="text-muted small">Loading general reports…</div>
                            </div>
                        </div>
                        <!-- Flow Data Container -->
                        <div id="flow-data-container" class="d-none">
                            <!-- Flow chains will be inserted here -->
                        </div>

                        

                        <!-- Overall Summary -->
                        <div id="overall-summary" class="card mt-2 d-none">
                            <div class="border-0 shadow-none card-header py-2">
                                <h6 class="mb-0">
                                    <i class="fas fa-chart-pie me-2 text-primary"></i>
                                    Overall Statistics
                                </h6>
                            </div>
                            <div class="border-0 shadow-none card-body p-3">
                                <div class="row g-2" id="summary-grid">
                                    <!-- Summary items will be inserted here -->
                                </div>
                            </div>
                        </div>
                    <?php else: ?>
                        <div class="alert alert-warning text-center">
                            <div class="mb-2"><i class="fas fa-search fa-lg"></i></div>
                            <h6>Event Not Found</h6>
                            <p class="mb-2 small">The requested event could not be found. Please check the URL and try again.</p>
                            <a href="admin_heat_config.php" class="btn btn-outline-primary btn-sm">
                                <i class="fas fa-arrow-left me-1"></i>Back to Heat Configuration
                            </a>
                        </div>
                    <?php endif; ?>
                </div>
            </div>
        </div>
    </div>

    <!-- Floating Controls -->
    <?php if ($event_data): ?>
        <!-- Refresh Button -->
        <div class="position-fixed bottom-0 end-0 m-3 z-3">
            <button class="btn btn-primary rounded-circle shadow d-inline-flex align-items-center justify-content-center p-2" onclick="loadFlowData()" title="Refresh Data" aria-label="Refresh">
                <i class="fas fa-sync-alt"></i>
            </button>
        </div>

        <!-- Auto Refresh Indicator -->
        <div id="refresh-indicator" class="position-fixed bottom-0 end-0 mb-4 me-3 z-3 d-none">
            <div class="alert alert-secondary py-1 px-2 mb-0 small">
                <i class="fas fa-sync-alt me-1"></i>Refreshing...
            </div>
        </div>

        <!-- Debug Toggle Button -->
        <div class="position-fixed bottom-0 end-0 mb-4 me-4 z-3">
            <button class="btn btn-warning btn-sm" onclick="toggleDebugPanel()" title="Toggle Debug Info" aria-label="Toggle Debug">
                <i class="fas fa-bug"></i>
            </button>
        </div>

    <?php endif; ?>
    <!-- Summary Results Modal (Bootstrap) -->
    <div class="modal fade" id="summaryModal" tabindex="-1" aria-labelledby="summaryModalTitle" aria-hidden="true">
        <div class="modal-dialog modal-xl modal-dialog-scrollable">
            <div class="modal-content">
                <div class="modal-header bg-primary text-white py-2">
                    <h6 class="modal-title" id="summaryModalTitle">
                        <i class="fas fa-trophy me-2" style="color: gold;"></i>
                        Heat Results
                    </h6>
                    <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body p-3" id="summaryModalBody">
                    <!-- Content will be inserted here -->
                </div>
            </div>
        </div>
    </div>

    <!-- Add this debug panel right after the event header -->
    <div class="container-fluid">
        <?php if ($event_data): ?>
            <!-- DEBUG PANEL - Remove in production -->
            <div id="debug-panel" class="card border-warning mb-2 d-none">
                <div class="border-0 shadow-none card-header bg-warning py-2">
                    <h6 class="mb-0">
                        <i class="fas fa-bug me-2"></i>Debug Information
                        <button class="btn btn-sm btn-outline-dark float-end" onclick="document.getElementById('debug-panel').style.display='none'">Hide</button>
                    </h6>
                </div>
                <div class="border-0 shadow-none card-body p-3">
                    <div class="row">
                        <div class="col-md-6">
                            <small><strong>Event ID:</strong> <?= htmlspecialchars($selected_event_id) ?><br>
                            <strong>API URL:</strong> <span id="debug-api-url">-</span><br>
                            <strong>Response Status:</strong> <span id="debug-status">-</span><br>
                            <strong>Load Time:</strong> <span id="debug-load-time">-</span></small>
                        </div>
                        <div class="col-md-6">
                            <small><strong>Flow Chains Found:</strong> <span id="debug-chains-count">-</span><br>
                            <strong>Total Heats:</strong> <span id="debug-heats-count">-</span><br>
                            <strong>Total Participants:</strong> <span id="debug-participants-count">-</span><br>
                            <strong>Last Updated:</strong> <span id="debug-last-update">-</span></small>
                        </div>
                    </div>
                    <div class="mt-2">
                        <strong class="small">Raw API Response:</strong>
                        <pre id="debug-raw-response" class="bg-light p-2 rounded small" style="max-height: 150px; overflow-y: auto;">Loading...</pre>
                    </div>
                </div>
            </div>
        <?php endif; ?>
    </div>


<script>
        const eventId = <?= json_encode($selected_event_id) ?>;
        let refreshInterval;
        let countdownInterval;
        let isLoading = false;
        let countdown = 0;
        
        // DEBUG: Add debugging flag
        const DEBUG_MODE = true; // Set to false in production
        
        function debugLog(message, data = null) {
            if (DEBUG_MODE) {
                console.log(`[Heat Flow Debug] ${message}`, data || '');
            }
        }

        // Configuration-based reports (mirror public_event_dashboard)
        const DASH_API = '../api/public_dashboard_api.php';
        let configurationsCache = null;

        function refreshGeneralReports(evtId) {
            fetch(`${DASH_API}?action=get_configurations&event_id=${encodeURIComponent(evtId)}`, { method: 'GET' })
                .then(r => r.json())
                .then(data => {
                    if (data.success) {
                        configurationsCache = data.configurations || [];
                        updateGeneralReports(evtId, configurationsCache);
                        // Also re-render per-heat report buttons if chains already drawn
                        document.querySelectorAll('[data-heat-number]')?.forEach(el => {
                            const hn = Number(el.getAttribute('data-heat-number'));
                            renderHeatReportButtons(hn);
                        });
                    } else {
                        document.getElementById('general-reports').innerHTML = `<div class="text-danger small">${data.message||'Failed to load'}</div>`;
                    }
                })
                .catch(err => {
                    console.error('Error refreshing reports:', err);
                    const gr = document.getElementById('general-reports');
                    if (gr) gr.innerHTML = `<div class="text-danger small">Network error</div>`;
                });
        }

        function buildFormatBtn(label, icon, href) {
            const disabled = !href;
            const safeHref = href || '#';
            return `
                <a class="btn btn-sm ${disabled ? 'btn-outline-secondary disabled' : 'btn-outline-primary'}" href="${safeHref}" target="_blank" rel="noopener">
                    <i class="fas ${icon} me-1"></i>${label}
                </a>
            `;
        }

    function buildReportGroup(title, group) {
            if (!group || typeof group !== 'object') return '';
            return `
                <div class="mb-2">
                    <div class="small text-muted mb-1"><i class="fas fa-file-alt me-1"></i>${title}</div>
                    <div class="btn-group" role="group">
                        ${buildFormatBtn('PDF', 'fa-file-pdf', group.pdf)}
                        ${buildFormatBtn('HTML', 'fa-file-code', group.html)}
                        ${buildFormatBtn('CSV', 'fa-file-csv', group.csv)}
                        ${buildFormatBtn('JSON', 'fa-code', group.json)}
                    </div>
                </div>
            `;
        }

        function getStartListLinks(heatNumber) {
            const base = `../api/start_list_api.php?event_id=${encodeURIComponent(eventId)}&heat_number=${encodeURIComponent(heatNumber)}`;
            return {
                pdf: `${base}&format=pdf`,
                html: `${base}&format=html`,
                csv: `${base}&format=csv`,
                json: `${base}&format=json`,
            };
        }

        function getSummaryLinks(heatNumber) {
            // Default to 1-2 runs; adjust when runsByHeat is available
            const runs = (window.runsByHeat && window.runsByHeat[heatNumber]) ? window.runsByHeat[heatNumber] : [1,2];
            const heatRunFilter = encodeURIComponent(JSON.stringify({ [heatNumber]: runs }));
            const common = `event_id=${encodeURIComponent(eventId)}&category=all&heat_run_filter=${heatRunFilter}`;
            const base = `../api/summary_table_api.php?${common}`;
            return {
                pdf: `${base}&format=pdf`,
                html: `${base}&format=html`,
                csv: `${base}&format=csv`,
                json: `${base}&format=json`,
            };
        }

        // Tooltips helper (safe if Bootstrap JS not present)
        function enableTooltips(root = document) {
            try {
                if (typeof bootstrap === 'undefined' || !bootstrap.Tooltip) return;
                root.querySelectorAll('[data-bs-toggle="tooltip"]').forEach(el => {
                    bootstrap.Tooltip.getOrCreateInstance(el);
                });
            } catch (_) { /* no-op */ }
        }

        // Pick the best summary config for a heat (prefer heat-level, fallback to event-level)
        function getDefaultSummaryConfig(heatNumber) {
            const configs = configurationsCache || [];
            const byHeat = configs.find(c => c.view_type === 'summary_table' && Number(c.heat_number) === Number(heatNumber));
            if (byHeat) return byHeat;
            const eventLevel = configs.find(c => c.view_type === 'summary_table' && (c.heat_number == null || c.heat_number === '' ));
            return eventLevel || null;
        }

        // Click handler: open the best available summary table for this heat
        function loadBestSummaryForHeat(heatNumber) {
            const cfg = getDefaultSummaryConfig(heatNumber);
            if (!cfg) {
                alert('No summary table configuration found for this heat.');
                return;
            }
            const safeName = String(cfg.name || 'Summary Table').replace(/'/g, "\\'");
            loadSummaryTableCard(eventId, heatNumber, cfg.id, safeName);
        }

        // Build small shortcuts toolbar HTML for a heat
        function getHeatShortcutToolbarHtml(heat) {
            const heatNumber = heat.heat_number;
            const csvHref = `../api/start_list_api.php?event_id=${encodeURIComponent(eventId)}&heat_number=${encodeURIComponent(heatNumber)}&format=csv`;
            const configHref = `admin_heat_config.php?event_id=${encodeURIComponent(eventId)}&heat_id=${encodeURIComponent(heatNumber)}`;
            const assignHref = `heat_management_modal.php?event_id=${encodeURIComponent(eventId)}&heat_id=${encodeURIComponent(heatNumber)}&mode=assign`;
            const judgeHref = `head_judge_override.php?event_id=${encodeURIComponent(eventId)}&heat_id=${encodeURIComponent(heatNumber)}`;
            const manageHref = `heat_management_modal.php?event_id=${encodeURIComponent(eventId)}&heat_id=${encodeURIComponent(heatNumber)}&standalone=1`;
            return `
                <div class="btn-group btn-group-sm" role="group" aria-label="Heat shortcuts">
                    
                    
                    
                    <a class="btn btn-outline-secondary" data-bs-toggle="tooltip" title="Assign Participants to Heats"
                       href="${assignHref}" target="_blank" rel="noopener">
                       <i class="fas fa-user-plus"></i>
                    </a>
                    <a class="btn btn-outline-secondary" data-bs-toggle="tooltip" title="Heat Management"
                       href="${manageHref}" target="_blank" rel="noopener">
                       <i class="fas fa-sliders"></i>
                    </a>
                    <a class="btn btn-outline-secondary" data-bs-toggle="tooltip" title="Head Judge Override"
                       href="${judgeHref}" target="_blank" rel="noopener">
                       <i class="fas fa-gavel"></i>
                    </a>
                    <button type="button" class="btn btn-outline-secondary" data-bs-toggle="tooltip" title="Promote to Heat"
                        onclick="promoteToHeat(${heatNumber})">
                        <i class="fas fa-arrow-up"></i>
                    </button>
                    <a class="btn btn-outline-secondary" data-bs-toggle="tooltip" title="Open Heat Config"
                       href="${configHref}" target="_blank" rel="noopener">
                       <i class="fas fa-cog"></i>
                    </a>
                </div>
            `;
        }

        // Promote participants from this heat to a target heat
        async function promoteToHeat(heatNumber) {
            try {
                const input = prompt('Promote to which target heat number?');
                if (!input) return;
                const targetHeat = parseInt(input, 10);
                if (!Number.isFinite(targetHeat) || targetHeat <= 0) {
                    alert('Please enter a valid target heat number.');
                    return;
                }
                const params = new URLSearchParams({
                    action: 'promote',
                    event_id: String(eventId || ''),
                    heat_id: String(heatNumber),
                    target_heat: String(targetHeat)
                });
                const url = `../api/summary_table_api.php?${params.toString()}`;
                const res = await fetch(url, { method: 'GET' });
                const text = await res.text();
                let data;
                try { data = JSON.parse(text); } catch (_) { data = { success: res.ok, message: text }; }
                if (!res.ok || data.success === false) {
                    throw new Error(data.message || `Request failed (${res.status})`);
                }
                alert(data.message || 'Promotion completed successfully.');
                // Optionally refresh flow data
                // loadFlowData();
            } catch (err) {
                alert(`Promotion failed: ${err.message}`);
            }
        }

        function updateGeneralReports(evtId, configurations = []) {
            const container = document.getElementById('general-reports');
            const card = document.getElementById('general-reports-card');
            if (!container || !card) return;

            card.classList.remove('d-none');
            const general = (configurations || []).filter(c => !c.heat_number);
            if (general.length === 0) {
                container.innerHTML = `<div class="text-muted small">No general reports available</div>`;
                return;
            }

            const summaryTables = general.filter(c => c.view_type === 'summary_table');
            const startLists = general.filter(c => c.view_type === 'start_list');

            let html = '<div class="row g-2">';
            if (summaryTables.length) {
                html += `
                    <div class="col-12">
                        <small class="text-muted">Summary Tables:</small>
                        <div class="d-flex flex-wrap gap-1 mt-1">
                            ${summaryTables.map(cfg => `
                                <button class="btn btn-sm btn-info"
                                    onclick="loadSummaryTableCard(${evtId}, null, ${cfg.id}, '${String(cfg.name).replace(/'/g, "\\'")}')">
                                    <i class="fas fa-table me-1"></i>${cfg.name}
                                </button>`).join('')}
                        </div>
                    </div>`;
            }
            if (startLists.length) {
                html += `
                    <div class="col-12">
                        <small class="text-muted">Start Lists:</small>
                        <div class="d-flex flex-wrap gap-1 mt-1">
                            ${startLists.map(cfg => `
                                <button class="btn btn-sm btn-success"
                                    onclick="loadStartListCard(${evtId}, null, ${cfg.id})">
                                    <i class="fas fa-users me-1"></i>${cfg.name}
                                </button>`).join('')}
                        </div>
                    </div>`;
            }
            html += '</div>';
            container.innerHTML = html;
        }

        function renderHeatReportButtons(heatNumber) {
            const holder = document.getElementById(`reports-${heatNumber}`);
            if (!holder) return;
            const configs = configurationsCache || [];
            const heatConfigs = configs.filter(c => Number(c.heat_number) === Number(heatNumber));
            if (!heatConfigs.length) {
                holder.innerHTML = '';
                return;
            }
            const btns = heatConfigs.map(cfg => {
                    const isSummary = cfg.view_type === 'summary_table';
                    const isStart = cfg.view_type === 'start_list';
                    const icon = isSummary ? 'fa-trophy' : (isStart ? 'fa-users' : 'fa-file');
                    const color = isSummary ? 'info' : (isStart ? 'success' : 'secondary');
                    const safeName = String(cfg.name || '').replace(/'/g, "\\'");
                    // Clean display label and build safe/encoded variants
                    const display = String(cfg.name || '')
                        .replace(/^Summary Table\s*-\s*/i, '')
                        .replace(/^Start List\s*-\s*/i, '');
                    const encName = encodeURIComponent(cfg.name || '');
                    let viewBtn = '';
                    let exportGroup = '';

                    if (isSummary) {
                        // View in modal
                        viewBtn = `<button class="btn btn-sm btn-${color} text-start" onclick="loadSummaryTableCard(${eventId}, ${heatNumber}, ${cfg.id}, '${safeName}')"><i class="fas ${icon} me-1" style="color: gold;"></i></i>${display}</button>`;
                        // Export buttons
                        const base = `../api/summary_table_api.php?config_id=${cfg.id}&config_name=${encName}`;
                        exportGroup = `
                            <div class="btn-group w-100" role="group">
                                <button type="button" onclick="window.open('${base}&format=pdf','_blank')" class="btn btn-sm btn-outline-danger border-0 p-0">
                                    <i class="fas fa-file-pdf"></i>
                                </button>
                                <button type="button" onclick="window.open('${base}&format=html','_blank')" class="btn btn-sm btn-outline-secondary border-0 p-0">
                                    <i class="fas fa-table"></i>
                                </button>
                                <button type="button" onclick="window.location.href='${base}&format=csv'" class="btn btn-sm btn-outline-primary border-0 p-0">
                                    <i class="fas fa-file-csv"></i>
                                </button>
                                <button type="button" onclick="window.open('${base}&format=json','_blank')" class="btn btn-sm btn-outline-success border-0 p-0">
                                    <i class="fas fa-code"></i>
                                </button>
                            </div>`;
                    } else if (isStart) {
                        // View in modal
                        viewBtn = `<button class="btn btn-sm btn-outline-${color} w-100 text-start" onclick="loadStartListCard(${eventId}, ${heatNumber}, ${cfg.id})"><i class="fas ${icon} me-1"></i>${cfg.name}</button>`;
                        // Export buttons
                        const base = `../api/start_list_api.php?event_id=${encodeURIComponent(eventId)}${heatNumber ? `&heat_number=${encodeURIComponent(heatNumber)}` : ''}&config_id=${cfg.id}`;
                        exportGroup = `
                            <div class="btn-group w-100" role="group">
                                <button type="button" onclick="window.open('${base}&format=pdf','_blank')" class="btn btn-sm btn-outline-danger border-0 p-0">
                                    <i class="fas fa-file-pdf"></i>
                                </button>
                                <button type="button" onclick="window.open('${base}&format=html','_blank')" class="btn btn-sm btn-outline-secondary border-0 p-0">
                                    <i class="fas fa-table"></i>
                                </button>
                                <button type="button" onclick="window.location.href='${base}&format=csv'" class="btn btn-sm btn-outline-primary border-0 p-0">
                                    <i class="fas fa-file-csv"></i>
                                </button>
                                <button type="button" onclick="window.open('${base}&format=json','_blank')" class="btn btn-sm btn-outline-success border-0 p-0">
                                    <i class="fas fa-code"></i>
                                </button>
                            </div>`;
                    } else {
                        return '';
                    }

                    return `
                        <div class="row g-1 align-items-stretch mb-2">
                            <div class="col-8">${viewBtn}</div>
                            <div class="col-4 d-flex align-items-center justify-content-end">${exportGroup}</div>
                        </div>
                    `;
                }).filter(Boolean).join('');
            holder.innerHTML = btns;
        }

    // Load flow data on page load
        document.addEventListener('DOMContentLoaded', function() {
            debugLog('Page loaded, eventId:', eventId);
            if (eventId) {
        // Load configurations for report buttons
        refreshGeneralReports(eventId);
                loadFlowData();
                setupAutoUpdate();
                
                // Setup interval selector change event
                document.getElementById('updateInterval').addEventListener('change', setupAutoUpdate);
            } else {
                debugLog('No event ID provided');
            }
        });

        function setupAutoUpdate() {
            const intervalSelect = document.getElementById('updateInterval');
            const intervalValue = parseInt(intervalSelect.value);
            
            // Clear existing intervals
            if (refreshInterval) {
                clearInterval(refreshInterval);
                refreshInterval = null;
            }
            if (countdownInterval) {
                clearInterval(countdownInterval);
                countdownInterval = null;
            }
            
            if (intervalValue > 0) {
                countdown = intervalValue;
                updateCountdownDisplay();
                
                // Set up refresh interval
                refreshInterval = setInterval(() => {
                    loadFlowData();
                    countdown = intervalValue;
                }, intervalValue * 1000);
                
                // Set up countdown interval
                countdownInterval = setInterval(() => {
                    countdown--;
                    updateCountdownDisplay();
                }, 1000);
            } else {
                document.getElementById('countdownTimer').textContent = '';
            }
        }
        
        function updateCountdownDisplay() {
            const timerElement = document.getElementById('countdownTimer');
            if (countdown > 0) {
                timerElement.textContent = `Next update in ${countdown}s`;
            } else {
                timerElement.textContent = 'Updating...';
            }
        }

         async function loadFlowData() {
            if (isLoading) {
                debugLog('Already loading, skipping request');
                return;
            }
            
            const startTime = performance.now();
            isLoading = true;
            showRefreshIndicator();
            debugLog('Starting to load flow data for event:', eventId);
            
            // Update debug panel
            updateDebugPanel('debug-api-url', `heat_flow_api.php?event_id=${eventId}`);
            updateDebugPanel('debug-status', 'Loading...');
            updateDebugPanel('debug-raw-response', 'Loading...');
            
            try {
                const url = `heat_flow_api.php?event_id=${eventId}`;
                debugLog('Requesting URL:', url);
                
                const response = await fetch(url);
                debugLog('Response status:', response.status);
                
                const responseText = await response.text();
                debugLog('Raw response text (first 500 chars):', responseText.substring(0, 500));
                
                // Update debug panel with raw response
                updateDebugPanel('debug-raw-response', responseText);
                updateDebugPanel('debug-status', `${response.status} ${response.statusText}`);
                
                let data;
                try {
                    data = JSON.parse(responseText);
                    debugLog('Parsed JSON data structure:', {
                        hasFlowChains: !!data.flow_chains,
                        flowChainsLength: data.flow_chains?.length || 0,
                        hasStatistics: !!data.statistics,
                        statisticsKeys: data.statistics ? Object.keys(data.statistics) : [],
                        hasResultsData: data.flow_chains ? data.flow_chains.some(chain => 
                            chain.some(heat => heat.summary_results && heat.summary_results.has_results)
                        ) : false
                    });
                } catch (parseError) {
                    debugLog('JSON parse error:', parseError);
                    updateDebugPanel('debug-status', `Parse Error: ${parseError.message}`);
                    throw new Error(`Failed to parse JSON response: ${parseError.message}`);
                }
                
                if (!response.ok) {
                    debugLog('HTTP error response:', data);
                    throw new Error(data.error || `HTTP ${response.status}: ${response.statusText}`);
                }
                
                // Update debug panel with parsed data
                const endTime = performance.now();
                const loadTime = Math.round(endTime - startTime);
                
                updateDebugPanel('debug-load-time', `${loadTime}ms`);
                updateDebugPanel('debug-chains-count', data.flow_chains?.length || 0);
                updateDebugPanel('debug-heats-count', data.statistics?.total_heats || 0);
                updateDebugPanel('debug-participants-count', data.statistics?.total_participants || 0);
                updateDebugPanel('debug-last-update', new Date().toLocaleTimeString());
                
                debugLog('Flow chains found:', data.flow_chains?.length || 0);
                debugLog('Statistics:', data.statistics);
                debugLog('Summary results available:', data.flow_chains ? 
                    data.flow_chains.map(chain => chain.map(heat => ({
                        heat: heat.heat_number,
                        hasResults: heat.summary_results?.has_results || false,
                        categoriesWithResults: Object.keys(heat.summary_results?.top_3_by_category || {})
                    }))) : []
                );
                
                renderFlowData(data);
                hideAllStates();
                document.getElementById('flow-data-container').classList.remove('d-none');
                document.getElementById('overall-summary').classList.remove('d-none');
                
            } catch (error) {
                debugLog('Error loading flow data:', error);
                console.error('Full error details:', error);
                updateDebugPanel('debug-status', `Error: ${error.message}`);
                showErrorState(`${error.message}\n\nCheck browser console for detailed logs or toggle debug panel for more info.`);
            } finally {
                isLoading = false;
                hideRefreshIndicator();
                debugLog('Load flow data completed');
            }
        }

        function updateDebugPanel(elementId, value) {
            const element = document.getElementById(elementId);
            if (element) {
                if (typeof value === 'object') {
                    element.textContent = JSON.stringify(value, null, 2);
                } else {
                    element.textContent = value;
                }
            }
        }

        function toggleDebugPanel() {
            const panel = document.getElementById('debug-panel');
            panel.classList.toggle('d-none');
        }

        function renderFlowData(data) {
            debugLog('Starting to render flow data');
            const container = document.getElementById('flow-data-container');
            const summaryGrid = document.getElementById('summary-grid');
            
            // Clear existing content
            container.innerHTML = '';
            summaryGrid.innerHTML = '';
            
            if (!data.flow_chains || data.flow_chains.length === 0) {
                debugLog('No flow chains found, showing empty state');
                showEmptyState();
                return;
            }
            
            debugLog('Processing flow chains:', data.flow_chains.length);
            
            // Calculate estimated times for chains
            const chainsWithTimes = calculateChainTimes(data.flow_chains);
            debugLog('Chains with calculated times:', chainsWithTimes);
            
            // Render each flow chain
            chainsWithTimes.forEach((chain, chainIndex) => {
                debugLog(`Rendering chain ${chainIndex + 1} with ${chain.length} heats`);
                const chainCard = createChainCard(chain, chainIndex);
                container.appendChild(chainCard);
            });
            
            // Render overall summary
            debugLog('Rendering summary with statistics:', data.statistics);
            renderSummary(data.statistics);
        }
        
        // Replace the calculateChainTimes function with this enhanced version
        function calculateChainTimes(chains) {
            return chains.map(chain => {
                let previousEndTime = null;
                let chainHasConflicts = false;
                
                return chain.map((heat, heatIndex) => {
                    const heatCopy = { ...heat };
                    let hasTimeConflict = false;
                    let delayMinutes = 0;
                    
                    // Calculate estimated duration
                    let estimatedDuration = 30; // Default 30 minutes
                    if (heat.participant_count > 0 && heat.estimate_time_per_participant > 0) {
                        estimatedDuration = Math.ceil((heat.estimate_time_per_participant * heat.participant_count) / 60);
                    }
                    heatCopy.estimated_duration = estimatedDuration;
                    
                    // Determine start time
                    let startTime;
                    let plannedStartTime = null;
                    let estimatedStartTime = null;
                    
                    if (heat.time_start) {
                        plannedStartTime = new Date(`2000-01-01 ${heat.time_start}`);
                        heatCopy.planned_start_time = heat.time_start;
                    }
                    
                    // Check if this heat should start after previous heat's end
                    if (previousEndTime && heatIndex > 0) {
                        // This heat should start after the previous heat ends
                        estimatedStartTime = new Date(previousEndTime);
                        heatCopy.estimated_start_time = estimatedStartTime.toTimeString().slice(0, 5);
                        
                        // Check for conflicts with planned time
                        if (plannedStartTime) {
                            if (estimatedStartTime > plannedStartTime) {
                                // Delay detected - estimated start is later than planned
                                hasTimeConflict = true;
                                delayMinutes = Math.ceil((estimatedStartTime - plannedStartTime) / (1000 * 60));
                                startTime = estimatedStartTime; // Use the later time
                                heatCopy.has_delay = true;
                                heatCopy.delay_minutes = delayMinutes;
                                chainHasConflicts = true;
                            } else {
                                // No conflict - use planned time
                                startTime = plannedStartTime;
                                // Update estimated start to match planned (no delay)
                                heatCopy.estimated_start_time = heat.time_start;
                            }
                        } else {
                            // No planned time, use estimated
                            startTime = estimatedStartTime;
                        }
                    } else if (plannedStartTime) {
                        // First heat or heat without previous dependency - use planned time
                        startTime = plannedStartTime;
                        heatCopy.estimated_start_time = heat.time_start;
                    } else {
                        // No planned time and no previous dependency - use current time or default
                        startTime = new Date();
                        startTime.setHours(8, 0, 0, 0); // Default to 8:00 AM
                        heatCopy.estimated_start_time = startTime.toTimeString().slice(0, 5);
                    }
                    
                    // Calculate end time
                    if (startTime) {
                        const endTime = new Date(startTime.getTime() + estimatedDuration * 60000);
                        heatCopy.estimated_end_time = endTime.toTimeString().slice(0, 5);
                        previousEndTime = endTime;
                        
                        // Store the actual start time used
                        heatCopy.actual_start_time = startTime.toTimeString().slice(0, 5);
                    }
                    
                    // Mark time conflict
                    heatCopy.has_time_conflict = hasTimeConflict;
                    
                    return heatCopy;
                });
            });
        }

        function createChainCard(chain, chainIndex) {
            const card = document.createElement('div');
            card.className = 'card mb-3';
            
            const hasConnections = chain.some((heat, idx) => 
                idx < chain.length - 1 && 
                chain[idx + 1].flow_source_heat == heat.heat_number
            );
            
            const totalParticipants = chain.reduce((sum, heat) => sum + heat.participant_count, 0);
            const flowHeats = chain.filter(heat => heat.flow_type !== 'none').length;
            const startingHeats = chain.filter(heat => 
                heat.flow_type === 'none' && !hasIncomingFlow(heat, chain)
            ).length;
            
            // Check for timing conflicts in the chain
            const hasChainConflicts = chain.some(heat => heat.has_time_conflict);
            const totalDelayMinutes = chain.reduce((sum, heat) => sum + (heat.delay_minutes || 0), 0);
            
            // Check for results availability in the chain
            const heatsWithResults = chain.filter(heat => heat.summary_results && heat.summary_results.has_results).length;
            
            let chainWarning = hasChainConflicts ? `<span class="badge bg-danger-subtle text-danger border border-danger-subtle">${totalDelayMinutes}min Delay</span>` : '';
            let resultsIndicator = heatsWithResults > 0 ? `<span class="badge bg-success-subtle text-success border border-success-subtle">${heatsWithResults} with Results</span>` : '';
            
            card.innerHTML = `
                <div class="border-0 shadow-none card-header d-flex justify-content-between align-items-center flex-wrap gap-2 py-2">
                    <div class="fw-bold">
                        <i class="fas fa-sitemap me-2"></i>
                        Chain ${chainIndex + 1} ${hasConnections ? '(Connected Flow)' : '(Independent Heats)'}
                        ${hasChainConflicts ? '<i class="fas fa-exclamation-triangle text-danger ms-2" title="Timing Conflicts Detected"></i>' : ''}
                    </div>
                    <div class="d-flex flex-wrap align-items-center gap-1">
                        <span class="badge text-bg-secondary small"><i class="fas fa-fire me-1"></i>${chain.length} Heat${chain.length > 1 ? 's' : ''}</span>
                        <span class="badge text-bg-secondary small"><i class="fas fa-users me-1"></i>${totalParticipants} Participants</span>
                        ${flowHeats > 0 ? `<span class="badge text-bg-secondary small"><i class="fas fa-route me-1"></i>${flowHeats} Auto Flow</span>` : ''}
                        ${startingHeats > 0 ? `<span class="badge text-bg-secondary small"><i class="fas fa-play me-1"></i>${startingHeats} Starting</span>` : ''}
                        ${resultsIndicator}
                        ${chainWarning}
                    </div>
                </div>
                <div class="border-0 shadow-none card-body bg-info-subtle p-3">
                <div class="d-flex align-items-center gap-2 overflow-auto">
                    ${chain.map((heat, idx) => {
                        const nextHeat = chain[idx + 1];
                        const hasConnection = nextHeat && nextHeat.flow_source_heat == heat.heat_number;
                        return createHeatNode(heat, idx, chain) + (hasConnection ? createFlowArrow(heat, nextHeat) : '');
                    }).join('')}
                </div>
                </div>
            `;
            // After inserting the chain, render per-heat report buttons and enable tooltips
            setTimeout(() => {
                chain.forEach(h => renderHeatReportButtons(h.heat_number));
                enableTooltips(card);
            }, 0);
            
            return card;
        }

        // Enhanced createHeatNode function with category-based results
        function createHeatNode(heat, index, chain) {
            const isActive = heat.is_active;
            const hasFlow = heat.flow_type !== 'none';
            const nextHeat = chain[index + 1];
            const hasConnection = nextHeat && nextHeat.flow_source_heat == heat.heat_number;
            const hasTimeConflict = heat.has_time_conflict;
            const hasDelay = heat.has_delay;
            
            // Enhanced time display with conflict detection
            let timeDisplay = '';
            if (heat.planned_start_time || heat.estimated_start_time) {
                timeDisplay = `
                    <div class="border-0 shadow-none card bg-light border-0 mb-2 p-2">
                        <div class="row g-1 small">
                `;
                
                if (heat.planned_start_time) {
                    const plannedEndTime = heat.estimated_end_time;
                    timeDisplay += `
                        <div class="col-12">
                            <div class="text-muted">
                                <i class="fas fa-calendar me-1 text-primary"></i>
                                <strong>Planned:</strong> ${heat.planned_start_time}${plannedEndTime ? ` - ${plannedEndTime}` : ''}
                                ${hasDelay ? `<span class="badge bg-warning text-dark ms-2">DELAYED ${heat.delay_minutes}min</span>` : ''}
                            </div>
                        </div>
                    `;
                }
                
                if (heat.estimated_start_time) {
                    const isAdjusted = heat.planned_start_time && heat.estimated_start_time !== heat.planned_start_time;
                    const estimatedClass = isAdjusted ? 'text-warning' : 'text-info';
                    timeDisplay += `
                        <div class="col-12">
                            <div class="${estimatedClass}">
                                <i class="fas fa-clock me-1"></i>
                                <strong>${isAdjusted ? 'Adjusted' : 'Estimated'}:</strong> ${heat.estimated_start_time}${heat.estimated_end_time ? ` - ${heat.estimated_end_time}` : ''}
                            </div>
                        </div>
                    `;
                }
                
                // Add duration and assignment type in the same row
                if (heat.estimated_duration) {
                    timeDisplay += `
                        <div class="col-6">
                            <div class="text-muted">
                                <i class="fas fa-hourglass-half me-1 text-secondary"></i>
                                <strong>Duration:</strong> ~${heat.estimated_duration}min
                            </div>
                        </div>
                    `;
                }
                
                // Add assignment type in the same card
                const hasIncoming = hasIncomingFlow(heat, chain);
                let assignmentType = '';
                if (hasFlow) {
                    if (heat.flow_type === 'promotion') {
                        assignmentType = `<span class="badge bg-warning-subtle text-warning border border-warning-subtle"><i class="fas fa-arrow-up me-1"></i>Auto Promotion</span>`;
                    } else if (heat.flow_type === 'qualifying') {
                        assignmentType = `<span class="badge bg-info-subtle text-info border border-info-subtle"><i class="fas fa-filter me-1"></i>Auto Qualifying</span>`;
                    }
                } else if (!hasIncoming) {
                    assignmentType = `<span class="badge bg-success-subtle text-success border border-success-subtle"><i class="fas fa-play me-1"></i>Starting Heat</span>`;
                } else {
                    assignmentType = `<span class="badge bg-warning-subtle text-warning border border-warning-subtle"><i class="fas fa-hand-paper me-1"></i>Manual Assignment</span>`;
                }
                
                if (assignmentType) {
                    timeDisplay += `
                        <div class="col-6">
                            <div class="d-flex align-items-center">
                                ${assignmentType}
                            </div>
                        </div>
                    `;
                }
                
                timeDisplay += `
                        </div>
                    </div>
                `;
                
                // Add delay warning if there's a conflict
                if (hasDelay) {
                    timeDisplay += `
                        <div class="alert alert-warning py-1 px-2 mb-2">
                            <i class="fas fa-exclamation-triangle me-1"></i>
                            <strong>Timing Conflict:</strong> Possible delay of ${heat.delay_minutes} minutes
                        </div>
                    `;
                }
            }
            
            // Participant Information Display
            let participantInfo = '';
            
            // Current participant (BIB on start)
            if (heat.current_participant) {
                participantInfo += `
                    <div class="border-0 shadow-none card border-success mb-2">
                        <div class="border-0 shadow-none card-header bg-success bg-opacity-10 py-1">
                            <i class="fas fa-play text-success me-1"></i>
                            <span class="fw-bold small">On Start:</span>
                        </div>
                        <div class="border-0 shadow-none card-body py-2">
                            <strong>BIB ${heat.current_participant.bib_number}</strong> - ${heat.current_participant.name}
                            ${heat.current_participant.category ? `<br><small class="text-muted">${heat.current_participant.category}</small>` : ''}
                        </div>
                    </div>
                `;
            }
            
            // Latest participant (completed run)
            if (heat.latest_participant) {
                participantInfo += `
                    <div class="border-0 shadow-none card border-warning mb-2">
                        <div class="border-0 shadow-none card-header bg-warning bg-opacity-10 py-1">
                            <i class="fas fa-flag-checkered text-warning me-1"></i>
                            <span class="fw-bold small">Latest Run:</span>
                        </div>
                        <div class="border-0 shadow-none card-body py-2">
                            <strong>BIB ${heat.latest_participant.bib_number}</strong> - ${heat.latest_participant.name}
                            ${heat.latest_participant.category ? `<br><small class="text-muted">${heat.latest_participant.category}</small>` : ''}
                        </div>
                    </div>
                `;
            }
            
            // Next participant
            if (heat.next_participant) {
                participantInfo += `
                    <div class="border-0 shadow-none card border-info mb-2">
                        <div class="border-0 shadow-none card-header bg-info bg-opacity-10 py-1">
                            <i class="fas fa-clock text-info me-1"></i>
                            <span class="fw-bold small">Next Up:</span>
                        </div>
                        <div class="border-0 shadow-none card-body py-2">
                            <strong>BIB ${heat.next_participant.bib_number}</strong> - ${heat.next_participant.name}
                            ${heat.next_participant.category ? `<br><small class="text-muted">${heat.next_participant.category}</small>` : ''}
                        </div>
                    </div>
                `;
            }
            
            // Progress information with scoring completion
            let progressInfo = '';
            if (heat.progress && heat.progress.total_participants > 0) {
                const progressPercentage = heat.progress.completion_percentage;
                const scoringPercentage = heat.progress.scoring_completion_percentage || 0;
                const progressVariant = progressPercentage >= 100 ? 'success' : progressPercentage >= 50 ? 'warning' : 'primary';
                progressInfo = `
                    <div class="border-0 shadow-none card border-secondary mb-2">
                        <div class="border-0 shadow-none card-header bg-secondary bg-opacity-10 py-1">
                            <i class="fas fa-chart-bar me-1"></i>
                            <span class="fw-bold small">Progress: ${heat.progress.completed_participants}/${heat.progress.total_participants}</span>
                            <span class="badge bg-${progressVariant} ms-2">${progressPercentage}%</span>
                        </div>
                        <div class="border-0 shadow-none card-body py-2">
                            <div class="progress mb-2" style="height: 15px;">
                                <div class="progress-bar bg-${progressVariant}" role="progressbar" style="width: ${progressPercentage}%" aria-valuenow="${progressPercentage}" aria-valuemin="0" aria-valuemax="100">${progressPercentage}%</div>
                            </div>
                            ${heat.progress.participants_with_scores ? `
                                <div class="d-flex align-items-center">
                                    <i class="fas fa-trophy me-1"></i>
                                    <span class="me-2 small">Scoring: ${heat.progress.participants_with_scores}/${heat.progress.total_participants}</span>
                                    <span class="badge bg-info">${scoringPercentage}%</span>
                                </div>
                            ` : ''}
                        </div>
                    </div>
                `;
            }
            
            // Flow info - detailed information for auto flows
            let flowInfo = '';
            if (hasFlow) {
                if (heat.flow_type === 'promotion') {
                    flowInfo = `
                        <div class="alert alert-warning py-1 px-2 mb-2">
                            <i class="fas fa-arrow-up me-1"></i>
                            <strong>Promotion Details:</strong> From Heat ${heat.flow_source_heat} • Top ${heat.flow_participants_per_category} per category
                        </div>
                    `;
                } else if (heat.flow_type === 'qualifying') {
                    flowInfo = `
                        <div class="alert alert-info py-1 px-2 mb-2">
                            <i class="fas fa-filter me-1"></i>
                            <strong>Qualifying Details:</strong> Top ${heat.flow_participants_per_category} per category advance
                        </div>
                    `;
                }
            }
            
            // Categories display - compact badges
            let categoriesDisplay = '';
            if (heat.categories && heat.categories.length > 0) {
                categoriesDisplay = `
                    <div class="mb-2">
                        <div class="d-flex flex-wrap gap-1 align-items-center">
                            <small class="text-muted me-1"><i class="fas fa-tags me-1"></i>Categories:</small>
                            ${heat.categories.map(cat => `<span class="badge text-bg-secondary small">${cat}</span>`).join('')}
                        </div>
                    </div>
                `;
            }
            
            // Add conflict indicator to heat node class
            let heatNodeClass = `card border-0 shadow-sm p-2 card-heat-node ${isActive ? 'border-success' : ''}`;
            if (hasTimeConflict) {
                heatNodeClass += ' border-danger';
            }
            
            // Enhanced Summary Results Section with Category-Based Results
            let summarySection = '';
            if (heat.summary_results && heat.summary_results.has_results) {
                const categoryResults = heat.summary_results.top_3_by_category || {};
                const combinedRankings = heat.summary_results.combined_rankings_by_category || {};
                const totalWithScores = heat.summary_results.total_with_scores || 0;
                
                summarySection = `
                    <div class="mt-2">
                        <div class="small mb-2">
                            <i class="fas fa-trophy me-1"></i>
                            ${totalWithScores} participants with scores
                        </div>
                `;
                
                // Display top 3 by category
                Object.keys(categoryResults).forEach(category => {
                    const top3 = categoryResults[category];
                    if (top3 && top3.length > 0) {
                        const leader = top3[0];
                        const score = leader.heat_average || leader.heat_best || leader.highest_score || '-';
                        
                        summarySection += `
                            <div class="mb-2">
                                <div class="d-flex align-items-center justify-content-between">
                                    <span class="badge text-bg-primary">${category}</span>
                                    <span class="text-muted small">
                                        Leader: BIB ${leader.bib_number} (${score})
                                    </span>
                                </div>
                                <div class="d-flex gap-2 flex-wrap">
                                    ${top3.map((participant, idx) => {
                                        const medals = ['🥇', '🥈', '🥉','',''];
                                        const participantScore = participant.heat_average || participant.heat_best || participant.highest_score || '-';
                                        return `
                                            <div class="border-0 shadow-none card border-0 bg-body-secondary p-2">
                                                <div class="fw-bold">${medals[idx]} BIB ${participant.bib_number}</div>
                                                <div>${participant.participant_name}</div>
                                                <div class="text-muted">${participantScore}</div>
                                            </div>
                                        `;
                                    }).join('')}
                                </div>
                                <button class="btn btn-outline-primary btn-sm mt-2" onclick="showCategorySummary(${heat.heat_number}, '${category}', '${heat.heat_name || `Heat ${heat.heat_number}`}', ${JSON.stringify(combinedRankings[category] || []).replace(/"/g, '&quot;')})">
                                    <i class="fas fa-table me-1"></i>
                                    Full ${category} Results
                                </button>
                            </div>
                        `;
                    }
                });
                
                // Overall summary button
                summarySection += `
                        <div class="d-flex gap-2 mt-2">
                            
                        </div>
                    </div>
                `;
            } else if (heat.summary_results && !heat.summary_results.success) {
                summarySection = `
                    <div class="mt-2">
                        
                    </div>
                `;
            } else {
                summarySection = `
                    <div class="mt-2">
                        
                    </div>
                `;
            }
            
        let nodeHtml = `
                <div class="${heatNodeClass}" style="min-width: 280px; max-width: 320px; position: relative;">
                    <!-- Heat Header -->
                    <div class="d-flex justify-content-between align-items-center mb-2">
                        <div class="fw-bold">
                            <i class="fas fa-fire me-1"></i>
                            ${heat.heat_name ? `${heat.heat_name}` : `Heat ${heat.heat_number}`}
                            ${hasDelay ? '<i class="fas fa-exclamation-triangle text-danger ms-1" title="Time Conflict"></i>' : ''}
                        </div>
                        <div class="d-flex align-items-center gap-2">
                            ${isActive ? `<span class="badge bg-success-subtle text-success border border-success-subtle">Run ${heat.active_run}</span>` : ''}
                            <a href="heat_management_modal.php?event_id=${encodeURIComponent(eventId)}&heat_id=${heat.heat_number}&standalone=1" 
                               class="btn btn-primary btn-sm"
                               target="_blank"
                               title="Heat Management">
                                <i class="fas fa-sliders-h"></i>
                            </a>
                        </div>
                    </div>
                    
                    <!-- Compact Info Row -->
                    <div class="row g-1 mb-2 small">
                        <div class="col-4 text-center">
                            <div class="text-muted">
                                <i class="fas fa-users me-1"></i>${heat.participant_count}
                            </div>
                        </div>
                        <div class="col-4 text-center">
                            <div class="text-muted">
                                <i class="fas fa-play me-1"></i>${heat.runs_count} run${heat.runs_count > 1 ? 's' : ''}
                            </div>
                        </div>
                        <div class="col-4 text-center">
                            <div class="text-muted">
                                <i class="fas fa-trophy me-1"></i>${heat.scoring_type}
                            </div>
                        </div>
                    </div>
                    
                    ${timeDisplay}
                    ${progressInfo}
                    ${summarySection}
                    <div id="reports-${heat.heat_number}" class="mt-2 card p-2"></div>
                </div>
            `;
            
            return nodeHtml;
        }

        function createFlowArrow(sourceHeat, targetHeat) {
            let arrowColor = 'text-secondary';
            let arrowIcon = 'fa-arrow-right';
            let arrowLabel = '';
            
            // Determine arrow style based on flow type
            if (targetHeat.flow_type === 'promotion') {
                arrowColor = 'text-warning';
                arrowIcon = 'fa-arrow-up';
                arrowLabel = 'Promotion';
            } else if (targetHeat.flow_type === 'qualifying') {
                arrowColor = 'text-info';
                arrowIcon = 'fa-filter';
                arrowLabel = 'Qualifying';
            } else if (targetHeat.flow_type === 'elimination') {
                arrowColor = 'text-danger';
                arrowIcon = 'fa-times';
                arrowLabel = 'Elimination';
            } else {
                arrowLabel = 'Flow';
            }
            
            return `
                <div class="d-flex flex-column align-items-center justify-content-center px-2" style="min-width: 60px;">
                    <i class="fas ${arrowIcon} ${arrowColor} fa-lg"></i>
                    <small class="${arrowColor} text-center mt-1" style="font-size: 0.7rem; line-height: 1;">${arrowLabel}</small>
                </div>
            `;
        }

        function hasIncomingFlow(heat, allHeats) {
            return allHeats.some(h => h.flow_source_heat == heat.heat_number);
        }

        function renderSummary(stats) {
            const summaryGrid = document.getElementById('summary-grid');
            
            const summaryItems = [
                { value: stats.total_heats, label: 'Total Heats', icon: 'fa-fire', color: '#ed8936' },
                { value: stats.flow_chains, label: 'Flow Chains', icon: 'fa-stream', color: '#4299e1' },
                { value: stats.auto_flow_heats, label: 'Auto Flow', icon: 'fa-route', color: '#48bb78' },
                { value: stats.starting_heats, label: 'Starting Heats', icon: 'fa-play', color: '#667eea' },
                { value: stats.total_participants, label: 'Total Participants', icon: 'fa-users', color: '#9f7aea' },
                { value: stats.active_heats, label: 'Active Heats', icon: 'fa-bolt', color: '#f56565' },
                { value: stats.heats_with_results || 0, label: 'Heats with Results', icon: 'fa-trophy', color: '#38a169' },
                { value: stats.total_participants_with_scores || 0, label: 'Participants Scored', icon: 'fa-medal', color: '#805ad5' }
            ];
            
            summaryItems.forEach(item => {
                const col = document.createElement('div');
                col.className = 'col-12 col-sm-6 col-lg-3';
                col.innerHTML = `
                    <div class="border-0 shadow-none card h-100">
                        <div class="border-0 shadow-none card-body p-2 text-center">
                            <div class="fs-5 fw-bold" style="color: ${item.color}">
                                <i class="fas ${item.icon} me-1"></i>
                                ${item.value}
                            </div>
                            <div class="text-muted small">${item.label}</div>
                        </div>
                    </div>`;
                summaryGrid.appendChild(col);
            });
        }

        function showErrorState(message) {
            hideAllStates();
            document.getElementById('error-message').textContent = message;
            document.getElementById('error-state').classList.remove('d-none');
        }

        function showEmptyState() {
            hideAllStates();
            document.getElementById('empty-state').classList.remove('d-none');
        }

        function hideAllStates() {
            document.getElementById('loading-state').classList.add('d-none');
            document.getElementById('error-state').classList.add('d-none');
            document.getElementById('empty-state').classList.add('d-none');
            document.getElementById('flow-data-container').classList.add('d-none');
            document.getElementById('overall-summary').classList.add('d-none');
        }

        function showRefreshIndicator() {
            document.getElementById('refresh-indicator').classList.remove('d-none');
        }

        function hideRefreshIndicator() {
            setTimeout(() => {
                document.getElementById('refresh-indicator').classList.add('d-none');
            }, 500);
        }

        // Cleanup on page unload
        window.addEventListener('beforeunload', function() {
            if (refreshInterval) {
                clearInterval(refreshInterval);
            }
            if (countdownInterval) {
                clearInterval(countdownInterval);
            }
        });

        // Pause auto-refresh when page is not visible
        document.addEventListener('visibilitychange', function() {
            if (document.hidden) {
                if (refreshInterval) {
                    clearInterval(refreshInterval);
                    refreshInterval = null;
                }
                if (countdownInterval) {
                    clearInterval(countdownInterval);
                    countdownInterval = null;
                }
            } else {
                if (eventId) {
                    setupAutoUpdate();
                }
            }
        });
        
        // Enhanced modal functions for category-based results
        
        function showHeatSummary(heatNumber, heatName, summaryResults) {
            const modal = document.getElementById('summaryModal');
            const modalTitle = document.getElementById('summaryModalTitle');
            const modalBody = document.getElementById('summaryModalBody');
            
            // Set modal title
            modalTitle.innerHTML = `
                <i class="fas fa-trophy"></i>
                ${heatName} - Complete Results
            `;
            
            // Build modal content with category grouping
            let modalContent = '';
            
            // Statistics Section
            if (summaryResults.statistics) {
                const stats = summaryResults.statistics;
                modalContent += `
                    <div class="summary-stats-row">
                        <div class="summary-stat-card">
                            <div class="summary-stat-value">${stats.total_participants || 0}</div>
                            <div class="summary-stat-label">Total Participants</div>
                        </div>
                        <div class="summary-stat-card">
                            <div class="summary-stat-value">${stats.participants_with_scores || 0}</div>
                            <div class="summary-stat-label">With Scores</div>
                        </div>
                        <div class="summary-stat-card">
                            <div class="summary-stat-value">${stats.categories_processed || 0}</div>
                            <div class="summary-stat-label">Categories</div>
                        </div>
                        <div class="summary-stat-card">
                            <div class="summary-stat-value">${Object.keys(summaryResults.combined_rankings_by_category || {}).length}</div>
                            <div class="summary-stat-label">With Results</div>
                        </div>
                    </div>
                `;
            }
            
            // Category-based results
            const categoryResults = summaryResults.combined_rankings_by_category || {};
            const top3ByCategory = summaryResults.top_3_by_category || {};
            
            if (Object.keys(categoryResults).length > 0) {
                modalContent += `<div class="category-results-container">`;
                
                Object.keys(categoryResults).forEach(category => {
                    const rankings = categoryResults[category];
                    const top3 = top3ByCategory[category] || [];
                    
                    if (rankings && rankings.length > 0) {
                        modalContent += `
                            <div class="mb-3">
                                <div class="d-flex align-items-center justify-content-between">
                                    <h5 class="mb-2">
                                        <span class="badge text-bg-primary">${category}</span>
                                    </h5>
                                    <span class="text-muted small">${rankings.length} participants</span>
                                </div>
                                
                                <!-- Top 3 for this category -->
                                ${top3.length > 0 ? `
                                    <div class="d-flex flex-wrap gap-2">
                                        ${top3.map((participant, index) => {
                                            const medals = ['🥇', '🥈', '🥉'];
                                            const score = participant.heat_average || participant.heat_best || participant.highest_score || '-';
                                            return `
                                                <div class="border-0 shadow-none card border-0 bg-body-secondary p-2">
                                                    <div class="fw-bold">${medals[index]} BIB ${participant.bib_number}</div>
                                                    <div>${participant.participant_name}</div>
                                                    <div class="text-muted">${score}</div>
                                                </div>
                                            `;
                                        }).join('')}
                                    </div>
                                ` : ''}
                                
                                <!-- Full rankings table for this category -->
                                <div class="table-responsive">
                                    <table class="table table-sm table-striped align-middle">
                                        <thead>
                                            <tr>
                                                <th>Rank</th>
                                                <th>BIB</th>
                                                <th>Participant</th>
                                                <th>Club</th>
                                                <th>Score</th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            ${rankings.slice(0, 10).map(participant => {
                                                const rankClass = getRankClass(participant.category_rank);
                                                const score = participant.heat_average || participant.heat_best || participant.highest_score || '-';
                                                
                                                return `
                                                    <tr>
                                                        <td><span class="rank-badge ${rankClass}">${participant.category_rank}</span></td>
                                                        <td><strong>${participant.bib_number}</strong></td>
                                                        <td>
                                                            <div class="participant-name">${participant.participant_name}</div>
                                                            <div class="participant-details">${participant.gender || ''}</div>
                                                        </td>
                                                        <td class="participant-details">${participant.club || '-'}</td>
                                                        <td><span class="score-badge">${score}</span></td>
                                                    </tr>
                                                `;
                                            }).join('')}
                                            ${rankings.length > 10 ? `
                                                <tr>
                                                    <td colspan="5" class="text-center">
                                                        <button class="btn btn-outline-primary btn-sm" onclick="showCategorySummary(${heatNumber}, '${category}', '${heatName}', ${JSON.stringify(rankings).replace(/"/g, '&quot;')})">
                                                            View All ${rankings.length} Results
                                                        </button>
                                                    </td>
                                                </tr>
                                            ` : ''}
                                        </tbody>
                                    </table>
                                </div>
                            </div>
                        `;
                    }
                });
                
                modalContent += `</div>`;
            } else {
                modalContent += `
                    <div class="no-results-message">
                        <i class="fas fa-chart-line"></i>
                        <h4>No Results Available</h4>
                        <p>This heat doesn't have any scoring results yet.</p>
                    </div>
                `;
            }
            
            modalBody.innerHTML = modalContent;
            const bsModal = new bootstrap.Modal(modal);
            bsModal.show();
        }
        
        // New function to show category-specific results
        function showCategorySummary(heatNumber, category, heatName, categoryRankings) {
            const modal = document.getElementById('summaryModal');
            const modalTitle = document.getElementById('summaryModalTitle');
            const modalBody = document.getElementById('summaryModalBody');
            
            // Set modal title
            modalTitle.innerHTML = `
                <i class="fas fa-medal"></i>
                ${heatName} - ${category} Results
            `;
            
            let modalContent = '';
            
            if (categoryRankings && categoryRankings.length > 0) {
                // Top 3 section
                const top3 = categoryRankings.slice(0, 3);
                if (top3.length > 0) {
                    modalContent += `
                        <div class="mb-2">
                            <h5><i class="fas fa-trophy me-2"></i>Top 3 - ${category}</h5>
                            <div class="d-flex flex-wrap gap-2">
                                ${top3.map((participant, index) => {
                                    const medals = ['🥇', '🥈', '🥉'];
                                    const score = participant.heat_average || participant.heat_best || participant.highest_score || '-';
                                    return `
                                        <div class="border-0 shadow-none card border-0 bg-body-secondary p-2">
                                            <div class="fw-bold">${medals[index]} BIB ${participant.bib_number}</div>
                                            <div>${participant.participant_name}</div>
                                            <div class="text-muted">${score}</div>
                                            <div class="small text-muted">${participant.club || ''}</div>
                                        </div>
                                    `;
                                }).join('')}
                            </div>
                        </div>
                    `;
                }
                
                // Full table
                modalContent += `
                    <div class="full-rankings-table">
                        <h5><i class="fas fa-list me-2"></i>Complete Rankings - ${category}</h5>
                        <table>
                            <thead>
                                <tr>
                                    <th style="width: 60px;">Rank</th>
                                    <th style="width: 80px;">BIB</th>
                                    <th>Participant</th>
                                    <th>Club</th>
                                    <th style="width: 80px;">Gender</th>
                                    <th style="width: 100px;">Score</th>
                                </tr>
                            </thead>
                            <tbody>
                `;
                
                categoryRankings.forEach(participant => {
                    const rankClass = getRankClass(participant.category_rank);
                    const score = participant.heat_average || participant.heat_best || participant.highest_score || '-';
                    
                    modalContent += `
                        <tr>
                            <td><span class="rank-badge ${rankClass}">${participant.category_rank}</span></td>
                            <td><strong>${participant.bib_number}</strong></td>
                            <td>
                                <div class="participant-name">${participant.participant_name}</div>
                            </td>
                            <td class="participant-details">${participant.club || '-'}</td>
                            <td class="participant-details">${participant.gender || '-'}</td>
                            <td><span class="score-badge">${score}</span></td>
                        </tr>
                    `;
                });
                
                modalContent += `
                            </tbody>
                        </table>
                    </div>
                `;
            } else {
                modalContent = `
                    <div class="no-results-message">
                        <i class="fas fa-chart-line"></i>
                        <h4>No Results for ${category}</h4>
                        <p>This category doesn't have any scoring results yet in this heat.</p>
                    </div>
                `;
            }
            
            modalBody.innerHTML = modalContent;
            const bsModal2 = new bootstrap.Modal(modal);
            bsModal2.show();
        }
        
        // New function to show full summary table (calls the summary table API directly)
        function showFullSummaryTable(heatNumber, heatName) {
            const modal = document.getElementById('summaryModal');
            const modalTitle = document.getElementById('summaryModalTitle');
            const modalBody = document.getElementById('summaryModalBody');
            
            // Set modal title
            modalTitle.innerHTML = `
                <i class="fas fa-table"></i>
                ${heatName} - Full Summary Table
            `;
            
            // Show loading state
            modalBody.innerHTML = `
                <div class="loading-state">
                    <div class="spinner-border" role="status">
                        <span class="visually-hidden">Loading...</span>
                    </div>
                    <p class="mt-3">Loading full summary table...</p>
                </div>
            `;
            
            const bsModal3 = new bootstrap.Modal(modal);
            bsModal3.show();
            
            // Fetch full summary table
            // Build heat_run_filter with heat number and runs in that heat
            // Example: {"1":[1,2,3]} for heat 1 with runs 1,2,3
            // For now, assume runs are 1..N (replace with actual runs if available)
            let runsInHeat = window.runsByHeat && window.runsByHeat[heatNumber] ? window.runsByHeat[heatNumber] : [1];
            // If you have a way to get actual runs, replace above logic
            const heatRunFilter = JSON.stringify({ [heatNumber]: '1,2,3' });
            const summaryUrl = `../api/summary_table_api.php?event_id=${eventId}&category=all&heat_run_filter={"${heatNumber}":[1,2]}&show_runs=true&show_judges=false&show_control_points=false&show_figures=false&show_heat_best=true&show_heat_average=false&sort=OverallAverage`;

            fetch(summaryUrl)
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        let tableContent = `
                            <div class="full-summary-table">
                                <div class="table-header">
                                    <h5>${heatName} - Complete Summary</h5>
                                    <div class="table-stats">
                                        <span class="badge bg-primary">${data.participant_count} Participants</span>
                                        ${data.is_grouped ? '<span class="badge bg-info">Grouped by Category</span>' : ''}
                                    </div>
                                </div>
                                <div class="table-responsive">
                                    <style>${data.table_badge_colors || ''}</style>
                                    <table class="table table-striped">
                                        ${data.table_head}
                                        ${data.table_body}
                                    </table>
                                </div>
                            </div>
                        `;
                        modalBody.innerHTML = tableContent;
                    } else {
                        modalBody.innerHTML = `
                            <div class="error-state">
                                <i class="fas fa-exclamation-triangle text-danger"></i>
                                <h4>Error Loading Summary Table</h4>
                                <p>${data.message || 'Failed to load the summary table data.'}</p>
                            </div>
                        `;
                    }
                })
                .catch(error => {
                    modalBody.innerHTML = `
                        <div class="error-state">
                            <i class="fas fa-exclamation-triangle text-danger"></i>
                            <h4>Error Loading Summary Table</h4>
                            <p>Failed to fetch the summary table: ${error.message}</p>
                        </div>
                    `;
                });
            
            // Add click outside to close
            modal.onclick = function(event) {
                if (event.target === modal) {
                    closeSummaryModal();
                }
            };
        }
        
        function getRankClass(rank) {
            if (rank === 1) return 'rank-1';
            if (rank === 2) return 'rank-2';
            if (rank === 3) return 'rank-3';
            return 'rank-other';
        }
        
        function closeSummaryModal() {
            const el = document.getElementById('summaryModal');
            const instance = bootstrap.Modal.getInstance(el) || new bootstrap.Modal(el);
            instance.hide();
        }
        
        // Close modal with Escape key
        // Bootstrap handles Escape key for modals automatically
        
        // Ensure Bootstrap JS is available
        if (typeof bootstrap === 'undefined') {
            console.warn('Bootstrap JS not detected. Ensure bootstrap.bundle.min.js is loaded.');
        }

        // Show Summary Table in modal instead of inline
        function loadSummaryTableCard(evtId, heatNumber, configId, configName) {
            const modal = document.getElementById('summaryModal');
            const modalTitle = document.getElementById('summaryModalTitle');
            const modalBody = document.getElementById('summaryModalBody');

            const heatLabel = heatNumber ? ` - Heat ${heatNumber}` : '';
            modalTitle.innerHTML = `<i class="fas fa-table me-2"></i>${configName || 'Summary Table'}${heatLabel}`;

            // Loading state
            modalBody.innerHTML = `
                <div class="text-center py-3">
                    <div class="spinner-border text-primary" role="status"></div>
                    <div class="mt-2 small text-muted">Loading summary table…</div>
                </div>
            `;

            // Open modal
            const bsModal = bootstrap.Modal.getOrCreateInstance(modal);
            bsModal.show();

            // Fetch content via server proxy for consistent rendering
            fetch('../public_event_dashboard.php', {
                method: 'POST',
                headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
                body: `ajax=1&action=load_summary_table&config_id=${encodeURIComponent(configId)}`
            })
            .then(r => r.json())
            .then(res => {
                if (!res || res.success !== true) {
                    throw new Error(res?.message || 'Failed to load summary table');
                }
                const data = res.data || {};
                const table_badge_colors = data.table_badge_colors || '';           
                const tableHead = data.table_head || '';
                const tableBody = data.table_body || '';
                const participantCount = data.participant_count;
                const filterSummary = data.filter_summary;

                const stats = (participantCount != null || filterSummary) ? `
                    <div class="d-flex flex-wrap gap-2 align-items-center mb-2">
                        ${participantCount != null ? `<span class="badge bg-primary">${participantCount} Participants</span>` : ''}
                        ${filterSummary ? `<span class="badge bg-info text-dark">${filterSummary}</span>` : ''}
                    </div>` : '';

                modalBody.innerHTML = `
                    ${stats}
                    <style>${table_badge_colors}</style>
                    <div class="table-responsive">
                        <table class="table table-sm table-striped table-hover mb-0">${tableHead}${tableBody}</table>
                    </div>
                `;
            })
            .catch(err => {
                modalBody.innerHTML = `
                    <div class="alert alert-danger mb-0">
                        <i class="fas fa-exclamation-triangle me-2"></i>${err.message}
                    </div>
                `;
            });
        }

        function loadStartListCard(evtId, heatNumber, configId = null) {
            const modal = document.getElementById('summaryModal');
            const modalTitle = document.getElementById('summaryModalTitle');
            const modalBody = document.getElementById('summaryModalBody');

            const heatLabel = heatNumber ? ` - Heat ${heatNumber}` : ' - All Heats';
            modalTitle.innerHTML = `<i class="fas fa-users me-2"></i>Start List${heatLabel}`;

            // Loading state
            modalBody.innerHTML = `
                <div class="text-center py-3">
                    <div class="spinner-border text-primary" role="status"></div>
                    <div class="mt-2 small text-muted">Loading start list…</div>
                </div>
            `;

            // Open modal
            const bsModal = bootstrap.Modal.getOrCreateInstance(modal);
            bsModal.show();

            fetch('../public_event_dashboard.php', {
                method: 'POST',
                headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
                body: `ajax=1&action=load_start_list&event_id=${encodeURIComponent(evtId)}${heatNumber ? `&heat_number=${encodeURIComponent(heatNumber)}` : ''}${configId ? `&config_id=${encodeURIComponent(configId)}` : ''}`
            })
            .then(r => r.json())
            .then(res => {
                if (!res || res.success !== true) {
                    throw new Error(res?.message || 'Failed to load start list');
                }
                const htmlContent = res.html_content || res.html || (res.data && (res.data.html_content || res.data.html)) || '';
                modalBody.innerHTML = `
                    <div style="max-height:70vh; overflow:auto;">
                        ${htmlContent || '<div class="alert alert-info mb-0">No participants found</div>'}
                    </div>
                `;
            })
            .catch(err => {
                modalBody.innerHTML = `
                    <div class="alert alert-danger mb-0">
                        <i class="fas fa-exclamation-triangle me-2"></i>${err.message}
                    </div>
                `;
            });
            // Log when notification system is ready
        setTimeout(() => {
            if (typeof globalNotificationManager !== 'undefined' && globalNotificationManager) {
                console.log('Heat Flow: Notification system loaded successfully');
            } else {
                console.warn('Heat Flow: Notification system not loaded');
            }
        }, 2000);
    }
    </script>
    
    <script>
    // Global test functions for notification system (outside any function scope)
    function testNotificationSystem() {
        // Try different methods in order of preference
        if (typeof globalNotificationManager !== 'undefined' && globalNotificationManager) {
            globalNotificationManager.sendNotification('info', 'Heat Flow Notification Test', 'Notification system is working on this page!', { test: true }, 'heat');
        } else if (typeof sendNotification === 'function') {
            sendNotification('info', 'Heat Flow Notification Test', 'Notification system is working on this page!', 'heat');
        } else if (typeof notifyInfo === 'function') {
            notifyInfo('Heat Flow Notification Test', 'Notification system is working on this page!');
        } else {
            // If no notification system available, show a simple alert and try to reinitialize
            alert('Notification system not yet loaded. Attempting to initialize...');
            
            // Try to manually initialize if the function exists
            if (typeof initializeNotificationSystem === 'function') {
                initializeNotificationSystem();
                setTimeout(() => {
                    if (typeof globalNotificationManager !== 'undefined' && globalNotificationManager) {
                        globalNotificationManager.sendNotification('success', 'Heat Flow System Ready', 'Notification system initialized successfully!', { test: true }, 'heat');
                    }
                }, 1000);
            } else {
                console.warn('Notification system initialization function not found');
            }
        }
    }
    
    function testHeatNotifications() {
        const heatNumber = Math.floor(Math.random() * 5) + 1;
        const runNumber = Math.floor(Math.random() * 3) + 1;
        
        if (typeof notifyHeat === 'function') {
            notifyHeat('activated', heatNumber, runNumber);
        } else if (typeof globalNotificationManager !== 'undefined' && globalNotificationManager) {
            globalNotificationManager.notifyHeatActivated(heatNumber, runNumber);
        } else {
            alert('Heat notification functions not available');
        }
    }
    
    function testParticipantNotifications() {
        const bibNumber = Math.floor(Math.random() * 50) + 1;
        const participantName = `Test Participant ${bibNumber}`;
        
        if (typeof notifyParticipant === 'function') {
            notifyParticipant('started', bibNumber, participantName);
        } else if (typeof globalNotificationManager !== 'undefined' && globalNotificationManager) {
            globalNotificationManager.notifyParticipantStarted(bibNumber, participantName);
        } else {
            alert('Participant notification functions not available');
        }
    }
    
    function testEmergencyStop() {
        if (typeof notifyEmergencyStop === 'function') {
            notifyEmergencyStop();
        } else if (typeof globalNotificationManager !== 'undefined' && globalNotificationManager) {
            globalNotificationManager.notifyEmergencyStop();
        } else {
            alert('Emergency stop notification not available');
        }
    }
    
    // Debug function to check what notification functions are available
    function debugNotificationSystem() {
        const available = [];
        const unavailable = [];
        
        const functions = [
            'globalNotificationManager',
            'sendNotification',
            'notifySuccess',
            'notifyError', 
            'notifyWarning',
            'notifyInfo',
            'notifyParticipant',
            'notifyHeat',
            'notifyJudge',
            'notifyScore',
            'notifyEmergencyStop',
            'initializeNotificationSystem'
        ];
        
        functions.forEach(func => {
            if (typeof window[func] !== 'undefined') {
                available.push(func);
            } else {
                unavailable.push(func);
            }
        });
        
        console.log('Available notification functions:', available);
        console.log('Unavailable notification functions:', unavailable);
        
        if (typeof globalNotificationManager !== 'undefined' && globalNotificationManager) {
            console.log('Global notification manager status:', globalNotificationManager.connectionStatus);
            console.log('Local mode:', globalNotificationManager.localMode);
            console.log('API available:', globalNotificationManager.apiAvailable);
        }
        
        alert(`Available: ${available.length} functions\nUnavailable: ${unavailable.length} functions\nCheck console for details.`);
    }
    </script>

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