// Static Dashboard JavaScript for Event ID: 3
class StaticLiveDashboard {
    constructor() {
        this.eventId = 3;
        this.refreshInterval = 30000; // 30 seconds
        this.lastUpdate = null;
        this.autoRefresh = true;
        this.refreshMs = 30000;
        this.activeReports = new Map();
        this.openHeatContainers = new Set();
        
        this.init();
    }
    
    init() {
        this.loadData();
        this.startAutoRefresh();
        this.updateLastUpdateTime();
        this.initializeControls();
    }
    
    initializeControls() {
        // Initialize refresh controls
        const refreshSelect = document.getElementById('refreshIntervalSelectMain');
        if (refreshSelect) {
            refreshSelect.addEventListener('change', (e) => {
                this.refreshMs = parseInt(e.target.value) || 30000;
                localStorage.setItem('dashboardRefreshMs', String(this.refreshMs));
                if (this.autoRefresh) {
                    this.startAutoRefresh();
                }
            });
        }
        
        // Initialize toggle refresh button
        const toggleBtn = document.getElementById('toggleRefresh');
        if (toggleBtn) {
            toggleBtn.addEventListener('click', () => this.toggleAutoRefresh());
        }
        
        // Add fullscreen support
        window.toggleDashboardFullscreen = () => this.toggleFullscreen();
        window.runRefreshCycle = () => this.loadData();
    }
    
    async loadData() {
        try {
            // Load events overview
            const eventsResponse = await fetch('api/events_overview.json?t=' + Date.now());
            const eventsData = await eventsResponse.json();
            
            if (eventsData.success && eventsData.events.length > 0) {
                await this.displayEvents(eventsData.events);
                this.lastUpdate = new Date();
                this.updateLastUpdateTime();
            } else {
                this.showError('No events found');
            }
        } catch (error) {
            console.error('Error loading data:', error);
            this.showError('Failed to load live data');
        }
    }
    
    async displayEvents(events) {
        const container = document.getElementById('eventsContainer');
        
        if (events.length === 0) {
            container.innerHTML = '<div class="col-12 py-2"><div class="alert alert-info">No active events found</div></div>';
            return;
        }

        let html = '';
        
        for (const event of events) {
            const isLive = ['in_progress','live'].includes(event.status);
            const nextBib = event.next_bib;
            
            // Auto-open heat containers for all events
            this.openHeatContainers.add(event.id);
            
            html += `
            <div class="row mb-3">
                <div class="col-4">
                    <div class="event-head-card card mb-0 border-0 shadow-sm bg-white" id="event-${event.id}">
                        <div class="card-header bg-gradient-primary text-white border-0 position-relative overflow-hidden py-2">
                            <div class="position-absolute top-0 end-0 opacity-10" style="font-size: 4rem; line-height: 1; color: rgba(255,255,255,0.1);">
                                <i class="fas fa-trophy"></i>
                            </div>
                            <div class="row align-items-center position-relative">
                                <div class="col-md-8">
                                    <h5 class="mb-1 fw-bold">
                                        <i class="fas fa-calendar-check me-2"></i>
                                        ${event.name}
                                    </h5>
                                    <p class="mb-0 text-white-50 small">
                                        <i class="fas fa-calendar me-1"></i>
                                        ${new Date(event.date).toLocaleDateString('en-US', { 
                                            weekday: 'long', 
                                            year: 'numeric', 
                                            month: 'long', 
                                            day: 'numeric' 
                                        })}
                                    </p>
                                </div>
                                <div class="col-md-4 text-end">
                                    <div class="d-flex flex-column align-items-end gap-1">
                                        ${isLive ? '<span class="badge bg-danger px-2 py-1 rounded-pill"><i class="fas fa-broadcast-tower me-1"></i>LIVE EVENT</span>' : ''}
                                        <span class="badge bg-light text-dark px-2 py-1 rounded-pill">
                                            <i class="fas fa-info-circle me-1"></i>
                                            ${event.status.replace('_',' ').toUpperCase()}
                                        </span>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div class="card-body p-3">
                            <!-- Event Statistics Row -->
                            <div class="row g-2 mb-3">
                                <div class="col-6 col-lg-4">
                                    <div class="d-flex align-items-center p-2 bg-primary bg-opacity-10 rounded">
                                        <div class="bg-primary text-white rounded-circle p-2 me-2" style="width: 35px; height: 35px; display: flex; align-items: center; justify-content: center;">
                                            <i class="fas fa-fire"></i>
                                        </div>
                                        <div>
                                            <div class="fw-bold text-primary">${event.current_heat || '—'}</div>
                                            <small class="text-muted">Active Heat</small>
                                        </div>
                                    </div>
                                </div>
                                <div class="col-6 col-lg-4">
                                    <div class="d-flex align-items-center p-2 bg-success bg-opacity-10 rounded">
                                        <div class="bg-success text-white rounded-circle p-2 me-2" style="width: 35px; height: 35px; display: flex; align-items: center; justify-content: center;">
                                            <i class="fas fa-play"></i>
                                        </div>
                                        <div>
                                            <div class="fw-bold text-success">${event.current_run || '—'}</div>
                                            <small class="text-muted">Current Run</small>
                                        </div>
                                    </div>
                                </div>
                                <div class="col-6 col-lg-4">
                                    <div class="d-flex align-items-center p-2 bg-info bg-opacity-10 rounded">
                                        <div class="bg-info text-white rounded-circle p-2 me-2" style="width: 35px; height: 35px; display: flex; align-items: center; justify-content: center;">
                                            <i class="fas fa-users"></i>
                                        </div>
                                        <div>
                                            <div class="fw-bold text-info">${event.total_participants || 0}</div>
                                            <small class="text-muted">Athletes</small>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            
                            <!-- Latest Updates Row -->
                            <div class="row g-2 mb-3" id="latest-updates-${event.id}">
                                <!-- Latest Score Section -->
                                <div class="col-md-12" id="latest-score-${event.id}">
                                    ${event.latest_score ? this.renderLatestScore(event.latest_score) : this.renderNoScore()}
                                </div>
                                
                                <!-- Next on Start Section -->
                                <div class="col-md-12" id="next-on-start-${event.id}">
                                    ${nextBib ? this.renderNextOnStart(nextBib) : this.renderNoNext()}
                                </div>
                            </div>
                            
                            <!-- Action Button -->
                            <div class="text-center">
                                <button class="btn btn-primary px-2 py-1 rounded-pill shadow-sm" onclick="window.dashboard.loadEventHeats(${event.id}, '${event.name.replace(/'/g,"&apos;")}')">
                                    <i class="fas fa-fire me-1"></i>
                                    View Heat Details
                                </button>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="col-8">
                    <!-- General Reports Section -->
                    <div class="col-12">
                        <div class="card h-100">
                            <div class="card-header bg-primary text-white d-flex align-items-center">
                                <i class="fas fa-chart-bar me-2"></i>
                                <span class="fw-bold">General Reports</span>
                            </div>
                            <div class="card-body p-3">
                                <div id="general-reports-${event.id}" class="general-reports-container">
                                    <div class="text-center text-muted">
                                        <div class="spinner-border spinner-border-sm me-2" role="status">
                                            <span class="visually-hidden">Loading...</span>
                                        </div>
                                        Loading general reports...
                                    </div>
                                </div>
                                <!-- General Report Cards Container -->
                                <div class="general-report-cards mt-3" id="general-report-cards-${event.id}"></div>
                            </div>
                        </div>
                    </div>
                    <!-- Heats Wrapper -->
                    <div id="heats-${event.id}" class="heat-wrapper" style="display:block;">
                        <div class='text-center py-2'><div class='spinner-border spinner-border-sm text-primary' role='status'></div><p class='mt-1 text-muted small'>Loading heat details...</p></div>
                    </div>
                </div>
            </div>`;
        }

        container.innerHTML = html;

        // Auto-load heat details for all events
        for (const event of events) {
            await this.loadEventHeatsData(event.id, event.name);
            // Load general reports for each event
            await this.refreshGeneralReports(event.id);
        }
        
        // Set global reference
        window.dashboard = this;
        
        // Make functions available globally for onclick handlers
        window.refreshGeneralReports = (eventId) => this.refreshGeneralReports(eventId);
        window.loadStartListCard = (eventId, heatNumber) => this.loadStartListCard(eventId, heatNumber);
        window.loadSummaryTableCard = (eventId, heatNumber, configId, configName) => this.loadSummaryTableCard(eventId, heatNumber, configId, configName);
    }
    
    renderLatestScore(score) {
        return `
            <div class="card border-0 bg-success bg-opacity-10 h-100">
                <div class="card-body p-2">
                    <div class="d-flex align-items-center mb-2">
                        <div class="bg-success text-white rounded-circle p-1 me-2" style="width: 30px; height: 30px; display: flex; align-items: center; justify-content: center;">
                            <i class="fas fa-trophy"></i>
                        </div>
                        <h6 class="mb-0 text-success fw-bold">Latest Score</h6>
                    </div>
                    <div class="d-flex align-items-center">
                        <div class="me-3">
                            ${this.createParticipantPhoto(score)}
                        </div>
                        <div class="flex-grow-1">
                            <div class="fw-bold">${score.first_name} ${score.last_name}</div>
                            <div class="d-flex gap-1 mb-1">
                                <span class="badge bg-dark">BIB ${score.bib_number}</span>
                                ${score.current_rank ? '<span class="badge bg-warning text-dark">#' + score.current_rank + '</span>' : ''}
                            </div>
                            <div class="h5 text-success mb-1">${parseFloat(score.score_value).toFixed(2)}</div>
                            <small class="text-muted">
                                <i class="fas fa-clock me-1"></i>
                                ${new Date(score.created_at).toLocaleTimeString()}
                            </small>
                        </div>
                    </div>
                </div>
            </div>
        `;
    }
    
    renderNoScore() {
        return `
            <div class="card border-0 bg-success bg-opacity-10 h-100">
                <div class="card-body p-2">
                    <div class="d-flex align-items-center mb-2">
                        <div class="bg-success text-white rounded-circle p-1 me-2" style="width: 30px; height: 30px; display: flex; align-items: center; justify-content: center;">
                            <i class="fas fa-trophy"></i>
                        </div>
                        <h6 class="mb-0 text-success fw-bold">Latest Score</h6>
                    </div>
                    <div class="text-center py-3 text-muted">
                        <i class="fas fa-clock fs-2 mb-2"></i>
                        <p class="mb-0 small">No scores yet</p>
                    </div>
                </div>
            </div>
        `;
    }
    
    renderNextOnStart(next) {
        return `
            <div class="card border-0 bg-primary bg-opacity-10 h-100">
                <div class="card-body p-2">
                    <div class="d-flex align-items-center mb-2">
                        <div class="bg-primary text-white rounded-circle p-1 me-2" style="width: 30px; height: 30px; display: flex; align-items: center; justify-content: center;">
                            <i class="fas fa-play"></i>
                        </div>
                        <h6 class="mb-0 text-primary fw-bold">Next on Start</h6>
                    </div>
                    <div class="d-flex align-items-center">
                        <div class="me-3">
                            ${this.createParticipantPhoto(next)}
                        </div>
                        <div class="flex-grow-1">
                            <div class="fw-bold">${next.first_name} ${next.last_name}</div>
                            <div class="d-flex gap-1 mb-1">
                                <span class="badge bg-dark">BIB ${next.bib_number}</span>
                                ${next.category ? '<span class="badge bg-info">' + next.category + '</span>' : ''}
                            </div>
                            <small class="text-primary">
                                <i class="fas fa-arrow-right me-1"></i>
                                Ready to compete
                            </small>
                        </div>
                    </div>
                </div>
            </div>
        `;
    }
    
    renderNoNext() {
        return `
            <div class="card border-0 bg-primary bg-opacity-10 h-100">
                <div class="card-body p-2">
                    <div class="d-flex align-items-center mb-2">
                        <div class="bg-primary text-white rounded-circle p-1 me-2" style="width: 30px; height: 30px; display: flex; align-items: center; justify-content: center;">
                            <i class="fas fa-play"></i>
                        </div>
                        <h6 class="mb-0 text-primary fw-bold">Next on Start</h6>
                    </div>
                    <div class="text-center py-3 text-muted">
                        <i class="fas fa-users fs-2 mb-2"></i>
                        <p class="mb-0 small">No participants waiting</p>
                    </div>
                </div>
            </div>
        `;
    }
    
    createParticipantPhoto(participant) {
        if (participant.photo && participant.photo.trim() !== '') {
            // Check if photo path needs adjustment for static files
            let photoPath = participant.photo;
            if (!photoPath.startsWith('http') && !photoPath.startsWith('photos/')) {
                // Assume it's a participant photo that was copied to photos directory
                if (photoPath.includes('participant_')) {
                    photoPath = 'photos/' + photoPath;
                } else {
                    // Skip showing photo if we can't determine the correct path
                    console.warn('Could not determine photo path for:', participant);
                    const initials = ((participant.first_name?.charAt(0) || '') + (participant.last_name?.charAt(0) || '')).toUpperCase() || '??';
                    return `<div class="participant-photo-placeholder">${initials}</div>`;
                }
            }
            
            return `<img src="${photoPath}" alt="${participant.first_name} ${participant.last_name}" class="participant-photo" onerror="this.style.display='none'; this.nextElementSibling.style.display='flex';">
                    <div class="participant-photo-placeholder" style="display:none;">${((participant.first_name?.charAt(0) || '') + (participant.last_name?.charAt(0) || '')).toUpperCase() || '??'}</div>`;
        } else {
            const initials = ((participant.first_name?.charAt(0) || '') + (participant.last_name?.charAt(0) || '')).toUpperCase() || '??';
            return `<div class="participant-photo-placeholder">${initials}</div>`;
        }
    }
    
    async loadEventHeats(eventId, eventName) {
        const container = document.getElementById(`heats-${eventId}`);
        if (container.style.display === 'none') {
            this.openHeatContainers.add(eventId);
            container.style.display = 'block';
            await this.loadEventHeatsData(eventId, eventName);
        } else {
            this.openHeatContainers.delete(eventId);
            this.activeReports.delete(`${eventId}`);
            container.style.display = 'none';
        }
    }
    
    async loadEventHeatsData(eventId, eventName) {
        const container = document.getElementById(`heats-${eventId}`);
        container.innerHTML = '<div class="text-center py-2"><div class="spinner-border spinner-border-sm" role="status"></div><p class="mt-1 small">Loading heat details...</p></div>';
        
        try {
            const response = await fetch('api/event_heats.json?t=' + Date.now());
            const data = await response.json();
            
            if (data.success) {
                this.displayHeats(eventId, eventName, data.heats, data.configurations);
            } else {
                container.innerHTML = '<div class="alert alert-danger">Error loading heats: ' + (data.message || 'Unknown') + '</div>';
            }
        } catch (error) {
            console.error('Error:', error);
            container.innerHTML = '<div class="alert alert-danger">Network error loading heats</div>';
        }
    }
    
    displayHeats(eventId, eventName, heats, configurations) {
        const container = document.getElementById(`heats-${eventId}`);
        if (!container) return;

        if (!heats || heats.length === 0) {
            container.innerHTML = `
                <div class="card mb-2">
                    <div class="card-header py-2"><strong>Heat Details</strong></div>
                    <div class="card-body p-2"><div class="alert alert-info mb-0 py-2">No heats configured for this event</div></div>
                </div>
            `;
            return;
        }

        let html = `
            <div class="card">
                <div class="card-header py-2"><strong>Heat Details</strong></div>
                <div class="card-body p-2">
                `;
        
        // Render each heat
        heats.forEach(heat => {
            const completion = heat.expected_scores > 0
                ? Math.round((Number(heat.total_scores || 0) / Number(heat.expected_scores)) * 100)
                : 0;
            const progressClass = completion >= 100 ? 'bg-success' : (completion >= 50 ? 'bg-warning' : 'bg-primary');
            const heatStatusClass = Number(heat.is_active) === 1 ? 'bg-danger' : (completion >= 100 ? 'bg-success' : 'bg-secondary');
            const heatStatusText = Number(heat.is_active) === 1 ? 'Live' : (completion >= 100 ? 'Completed' : 'Upcoming');

            html += `
                <div class="border rounded mb-3 p-3" id="event-${eventId}-heat-${heat.heat_number}">
                    <div class="row align-items-center">
                        <div class="col-md-6">
                            <div class="d-flex align-items-center">
                                <span class="badge ${heatStatusClass} me-2 px-2 py-1">${heatStatusText}</span>
                                <div>
                                    <strong class="h6 mb-0">Heat ${heat.heat_number}${heat.heat_name ? ': ' + heat.heat_name : ''}</strong>
                                    <div class="text-muted small">
                                        <i class="fas fa-clock me-1"></i>${heat.time_start || 'No time set'}
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div class="col-md-2 text-center">
                            <div class="bg-primary text-white rounded-circle p-2 mx-auto" style="width: 40px; height: 40px; display: flex; align-items: center; justify-content: center;">
                                <span class="text-white">${heat.participants || 0}</span>
                            </div>
                            <small class="text-muted">Athletes</small>
                        </div>
                        <div class="col-md-4">
                            <div class="text-center">
                                <div class="progress mb-1" style="height:8px;">
                                    <div class="progress-bar ${progressClass}" style="width:${completion}%;"></div>
                                </div>
                                <small class="fw-bold ${completion >= 100 ? 'text-success' : 'text-muted'}">${completion}% Complete</small>
                            </div>
                        </div>
                    </div>
                    
                    <!-- Available Reports Section -->
                    <div class="row mt-2 pt-2 border-top">
                        <div class="col-12">
                            <div class="d-flex align-items-center justify-content-between mb-3">
                                <small class="text-muted fw-bold">Available Reports:</small>
                            </div>
                            <div class="row g-3">
                                <!-- Start Lists Column -->
                                <div class="col-md-6">
                                    <div class="d-flex align-items-center mb-2">
                                        <i class="fas fa-users text-success me-2"></i>
                                        <small class="text-muted fw-bold">Start Lists</small>
                                    </div>
                                    <div class="d-flex flex-column gap-2">
                                        <button class="btn btn-outline-success btn-sm w-100 text-start" onclick="loadStartListCard(${eventId}, ${heat.heat_number})" title="Heat ${heat.heat_number} Start List">
                                            <i class="fas fa-users me-2"></i>Heat ${heat.heat_number} Start List
                                            <span class="badge ${heatStatusClass} float-end">${heatStatusText}</span>
                                        </button>
                                    </div>
                                </div>
                                
                                <!-- Summary Tables Column -->
                                <div class="col-md-6">
                                    <div class="d-flex align-items-center mb-2">
                                        <i class="fas fa-table text-info me-2"></i>
                                        <small class="text-muted fw-bold">Summary Tables</small>
                                    </div>
                                    <div class="d-flex flex-column gap-2">
                                        <button class="btn btn-outline-info btn-sm w-100 text-start" onclick="loadSummaryTableCard(${eventId}, ${heat.heat_number}, 1, 'Heat ${heat.heat_number} Results')" title="Heat ${heat.heat_number} Results">
                                            <i class="fas fa-table me-2"></i>Heat ${heat.heat_number} Results
                                            <span class="badge ${heatStatusClass} float-end">${heatStatusText}</span>
                                        </button>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    
                    <!-- Report Cards Container for this Heat -->
                    <div class="report-cards mt-3" id="report-cards-${eventId}-${heat.heat_number}"></div>
                </div>`;
        });

        html += `
                </div>
            </div>`;
        container.innerHTML = html;
    }
    
    startAutoRefresh() {
        if (this.refreshInterval) {
            clearInterval(this.refreshInterval);
        }
        this.refreshInterval = setInterval(() => {
            if (this.autoRefresh) {
                this.loadData();
            }
        }, this.refreshMs);
    }
    
    updateLastUpdateTime() {
        const element = document.getElementById('lastUpdate');
        if (element && this.lastUpdate) {
            element.textContent = this.lastUpdate.toLocaleTimeString();
        }
    }
    
    toggleAutoRefresh() {
        const toggleBtn = document.getElementById('toggleRefresh');
        if (!toggleBtn) return;
        
        if (this.autoRefresh) {
            this.autoRefresh = false;
            toggleBtn.innerHTML = '<i class="fas fa-play me-1"></i>Resume Updates';
        } else {
            this.autoRefresh = true;
            toggleBtn.innerHTML = '<i class="fas fa-pause me-1"></i>Pause Updates';
        }
    }
    
    // Report loading functions
    async refreshGeneralReports(eventId) {
        const container = document.getElementById('general-reports-' + eventId);
        if (!container) {
            console.error('General reports container not found for event', eventId);
            return;
        }
        
        container.innerHTML = '<div class="text-muted small">Loading general reports…</div>';
        
        try {
            // Load all configurations for this event
            const response = await fetch('api/configurations.json?t=' + Date.now());
            const data = await response.json();
            
            console.log('Configurations loaded:', data);
            
            if (data.success && data.configurations && data.configurations.length > 0) {
                // Group configurations by type
                const startListConfigs = data.configurations.filter(config => config.view_type === 'start_list');
                const summaryTableConfigs = data.configurations.filter(config => config.view_type === 'summary_table');
                
                console.log('Start lists found:', startListConfigs.length);
                console.log('Summary tables found:', summaryTableConfigs.length);
                
                let html = '';
                
                // Start Lists Section
                if (startListConfigs.length > 0) {
                    html += '<div class="mb-3">';
                    html += '<h6 class="text-success mb-2"><i class="fas fa-users me-2"></i>Start Lists</h6>';
                    html += '<div class="row g-2">';
                    startListConfigs.forEach(config => {
                        const heatText = config.heat_number ? ('H' + config.heat_number) : 'all';
                        const displayName = config.name;
                        const safeConfigName = config.name.replace(/'/g, "\\'");
                        html += '<div class="col-md-6">' +
                                  '<button class="btn btn-outline-success btn-sm w-100 text-start" onclick="window.dashboard.loadGeneralReport(' + this.eventId + ', ' + config.id + ', \'' + config.view_type + '\', \'' + safeConfigName + '\')">' +
                                    '<i class="fas fa-users me-2"></i>' + displayName +
                                    '<span class="badge bg-success float-end">' + heatText + '</span>' +
                                  '</button>' +
                                '</div>';
                    });
                    html += '</div></div>';
                }
                
                // Summary Tables Section  
                if (summaryTableConfigs.length > 0) {
                    html += '<div class="mb-3">';
                    html += '<h6 class="text-info mb-2"><i class="fas fa-table me-2"></i>Summary Tables</h6>';
                    html += '<div class="row g-2">';
                    summaryTableConfigs.forEach(config => {
                        const heatText = config.heat_number ? ('H' + config.heat_number) : 'all';
                        const displayName = config.name;
                        const safeConfigName = config.name.replace(/'/g, "\\'");
                        html += '<div class="col-md-6">' +
                                  '<button class="btn btn-outline-info btn-sm w-100 text-start" onclick="window.dashboard.loadGeneralReport(' + this.eventId + ', ' + config.id + ', \'' + config.view_type + '\', \'' + safeConfigName + '\')">' +
                                    '<i class="fas fa-table me-2"></i>' + displayName +
                                    '<span class="badge bg-info float-end">' + heatText + '</span>' +
                                  '</button>' +
                                '</div>';
                    });
                    html += '</div></div>';
                }
                
                if (html) {
                    container.innerHTML = html;
                } else {
                    container.innerHTML = '<div class="text-muted small">No reports configured</div>';
                }
            } else {
                // Show default reports even if no configurations found
                container.innerHTML = `
                    <div class="row g-2">
                        <div class="col-md-6">
                            <button class="btn btn-outline-success btn-sm w-100 text-start" onclick="window.dashboard.loadGeneralReport(, 1, 'start_list', 'Event Start List')">
                                <i class="fas fa-users me-2"></i>Event Start List
                            </button>
                        </div>
                        <div class="col-md-6">
                            <button class="btn btn-outline-info btn-sm w-100 text-start" onclick="window.dashboard.loadGeneralReport(, 2, 'summary_table', 'Event Results')">
                                <i class="fas fa-table me-2"></i>Event Results
                            </button>
                        </div>
                    </div>
                `;
            }
        } catch (error) {
            console.error('Error loading configurations:', error);
            container.innerHTML = '<div class="text-muted small">Error loading reports</div>';
        }
    }
    
    async loadGeneralReport(eventId, configId, viewType, configName) {
        // This would load the actual report content
        alert('Loading: ' + configName + ' (Event-level ' + viewType + ')');
    }
    
    async loadStartListCard(eventId, heatNumber) {
        // Load start list for specific heat
        try {
            const response = await fetch(`api/start_list_heat_${heatNumber}.json?t=` + Date.now());
            const data = await response.json();
            
            if (data.success && data.data && data.data.participants) {
                this.displayStartListModal(eventId, heatNumber, data.data.participants);
            } else {
                alert('No start list data available for Heat ' + heatNumber);
            }
        } catch (error) {
            console.error('Error loading start list:', error);
            alert('Error loading start list for Heat ' + heatNumber);
        }
    }
    
    async loadSummaryTableCard(eventId, heatNumber, configId, configName) {
        // Load summary table for specific heat
        try {
            const response = await fetch(`api/summary_table_${configId}.json?t=` + Date.now());
            const data = await response.json();
            
            if (data.success) {
                this.displaySummaryTableModal(eventId, heatNumber, configName, data);
            } else {
                alert('No summary table data available for ' + configName);
            }
        } catch (error) {
            console.error('Error loading summary table:', error);
            alert('Error loading summary table: ' + configName);
        }
    }
    
    displayStartListModal(eventId, heatNumber, participants) {
        // Simple display - in a real implementation this would show a modal
        let content = `Heat ${heatNumber} Start List:\n\n`;
        participants.forEach((p, index) => {
            content += `${index + 1}. Bib ${p.bib_number}: ${p.first_name} ${p.last_name}`;
            if (p.club) content += ` (${p.club})`;
            content += '\n';
        });
        alert(content);
    }
    
    displaySummaryTableModal(eventId, heatNumber, configName, data) {
        // Simple display - in a real implementation this would show a modal
        let content = `${configName}:\n\n`;
        if (data.rows && data.rows.length > 0) {
            data.rows.forEach((row, index) => {
                content += `${index + 1}. ${row.first_name} ${row.last_name}: ${row.best_score || 'No score'}\n`;
            });
        } else {
            content = 'No results available yet for ' + configName;
        }
        alert(content);
    }
    
    toggleFullscreen() {
        const container = document.getElementById('eventsContainer');
        if (!container) return;
        
        if (document.fullscreenElement) {
            document.exitFullscreen();
        } else {
            if (container.requestFullscreen) {
                container.requestFullscreen();
                container.classList.add('fullscreen');
            } else if (container.webkitRequestFullscreen) {
                container.webkitRequestFullscreen();
                container.classList.add('fullscreen');
            } else if (container.mozRequestFullScreen) {
                container.mozRequestFullScreen();
                container.classList.add('fullscreen');
            } else if (container.msRequestFullscreen) {
                container.msRequestFullscreen();
                container.classList.add('fullscreen');
            }
        }
    }
    
    showError(message) {
        const container = document.getElementById('eventsContainer');
        container.innerHTML = `
            <div class="alert alert-danger">
                <h4><i class="fas fa-exclamation-triangle me-2"></i>Error</h4>
                <p>${message}</p>
                <button class="btn btn-outline-danger" onclick="location.reload()">
                    <i class="fas fa-refresh me-2"></i>Reload
                </button>
            </div>
        `;
    }
}

// Initialize dashboard when page loads
document.addEventListener('DOMContentLoaded', function() {
    new StaticLiveDashboard();
});

// Handle fullscreen changes
document.addEventListener('fullscreenchange', function() {
    const container = document.getElementById('eventsContainer');
    if (container && !document.fullscreenElement) {
        container.classList.remove('fullscreen');
    }
});

// Report management globals
const activeReports = new Map();
const refreshMs = 30000; // 30 seconds default

// Load Summary Table Card with FLIP animations
function loadSummaryTableCard(eventId, heatNumber, configId, configName, options = {}) {
    const refresh = options.refresh === true;
    const reportKey = `${eventId}-${heatNumber ?? 'all'}-summary`;
    const holderId = `report-cards-${eventId}-${heatNumber ?? 'all'}`;
    let holder = document.getElementById(holderId);
    if (!holder && heatNumber == null) {
        holder = document.getElementById(`general-report-cards-${eventId}`) 
              || document.querySelector(`[id^="report-cards-${eventId}-"]`);
    }
    if (!holder) return;

    // Toggle only on direct button click, not on refresh
    if (!refresh && activeReports.has(reportKey) && activeReports.get(reportKey).configId === configId) {
        activeReports.delete(reportKey);
        morphHtml(holder, '');
        return;
    }

    const hadContent = holder.innerHTML.trim().length > 0;
    if (hadContent) showReportUpdating(reportKey);
    else {
        morphHtml(holder, `
            <div class="border-0 shadow-none card mb-3">
                <div class="border-0 shadow-none card-header d-flex justify-content-between align-items-center py-2">
                    <small class="fw-bold"><i class="fas fa-table me-1"></i>${configName}</small>
                    <div class="d-flex align-items-center gap-1 table-buttons">
                        <span class="badge bg-info"><i class="fas fa-sync-alt fa-spin me-1"></i>Loading…</span>
                        <button class="btn btn-sm btn-close btn-close-white" onclick="closeReportCard('${reportKey}')"></button>
                    </div>
                </div>
                <div class="border-0 shadow-none card-body p-2 text-center">
                    <div class="spinner-border spinner-border-sm text-primary"></div>
                    <small class="ms-2">Loading summary table…</small>
                </div>
            </div>`);
    }

    // Use static API endpoint instead of POST
    const apiUrl = `api/summary_table_${configId}.json?t=${Date.now()}`;
    
    fetch(apiUrl)
    .then(r => r.json())
    .then(res => {
        if (!res.success) throw new Error(res.message || 'Failed to load summary table');

        // FLIP: capture "First" positions BEFORE DOM update
        const prevRects = getRowRects(reportKey);

        const prev = activeReports.get(reportKey);
        const auto = prev ? (prev.auto !== false) : true;
        const html = convertSummaryTableToHTML(res.data, configName, reportKey, { auto });

        // Morph in new HTML (the order may change)
        morphHtml(holder, html);

        // FLIP: get "Last" and animate to new positions
        playFlipAnimation(reportKey, prevRects);

        // Track changes for animation
        let maps;
        if (refresh && prev && prev.type === 'summary_table') {
            maps = trackAndAnimateSummaryTable(reportKey, prev);
        } else {
            maps = buildSummaryRowMaps(reportKey);
        }

        activeReports.set(reportKey, {
            html,
            type: 'summary_table',
            configId,
            configName,
            auto,
            rowIndexMap: maps.indexMap,
            rowContentMap: maps.contentMap
        });
        
        console.log('Report loaded successfully:', configName);
    })
    .catch(err => {
        console.error('Error loading report:', err);
        if (!hadContent) {
            morphHtml(holder, `
                <div class="border-0 shadow-none card mb-3">
                    <div class="border-0 shadow-none card-header d-flex justify-content-between align-items-center py-2">
                        <small class="fw-bold"><i class="fas fa-table me-1"></i>${configName}</small>
                        <button class="btn btn-sm btn-close btn-close-white" onclick="closeReportCard('${reportKey}')"></button>
                    </div>
                    <div class="border-0 shadow-none card-body p-2"><div class="alert alert-danger py-2 mb-0">${err.message}</div></div>
                </div>`);
        }
    });
}

// Load Start List Card
function loadStartListCard(eventId, heatNumber) {
    const reportKey = `${eventId}-${heatNumber}-startlist`;
    const holderId = `report-cards-${eventId}-${heatNumber}`;
    const holder = document.getElementById(holderId);
    if (!holder) return;

    // Toggle if already loaded
    if (activeReports.has(reportKey)) {
        activeReports.delete(reportKey);
        morphHtml(holder, '');
        return;
    }

    morphHtml(holder, `
        <div class="border-0 shadow-none card mb-3">
            <div class="border-0 shadow-none card-header d-flex justify-content-between align-items-center py-2">
                <small class="fw-bold"><i class="fas fa-users me-1"></i>Heat ${heatNumber} Start List</small>
                <button class="btn btn-sm btn-close btn-close-white" onclick="closeReportCard('${reportKey}')"></button>
            </div>
            <div class="border-0 shadow-none card-body p-2 text-center">
                <div class="spinner-border spinner-border-sm text-primary"></div>
                <small class="ms-2">Loading start list…</small>
            </div>
        </div>`);

    // Use static API endpoint
    const apiUrl = `api/start_list.json?t=${Date.now()}`;
    
    fetch(apiUrl)
    .then(r => r.json())
    .then(res => {
        if (!res.success) throw new Error(res.message || 'Failed to load start list');
        
        const html = convertStartListToHTML(res.data, heatNumber, reportKey);
        morphHtml(holder, html);
        
        activeReports.set(reportKey, {
            html,
            type: 'start_list',
            heatNumber
        });
    })
    .catch(err => {
        console.error('Error loading start list:', err);
        morphHtml(holder, `
            <div class="border-0 shadow-none card mb-3">
                <div class="border-0 shadow-none card-header d-flex justify-content-between align-items-center py-2">
                    <small class="fw-bold"><i class="fas fa-users me-1"></i>Heat ${heatNumber} Start List</small>
                    <button class="btn btn-sm btn-close btn-close-white" onclick="closeReportCard('${reportKey}')"></button>
                </div>
                <div class="border-0 shadow-none card-body p-2"><div class="alert alert-danger py-2 mb-0">${err.message}</div></div>
            </div>`);
    });
}

// Convert summary table API data to HTML
function convertSummaryTableToHTML(apiData, configName, reportKey, opts = {}) {
    const auto = opts.auto !== false;
    const table_badge_colors = apiData?.table_badge_colors || '';
    const tableHead = apiData?.table_head || '';
    const tableBody = apiData?.table_body || '';
    const participantCount = apiData?.participant_count ?? 0;
    const filterSummary = apiData?.filter_summary || '';

    const tableHTML = (tableHead || tableBody) ? `
        <div class="d-flex justify-content-between align-items-center mb-2">
            <div class="d-flex align-items-center gap-2">
                <span class="badge bg-primary">${participantCount} Participants</span>
                ${auto ? `<span class="badge bg-success"><i class="fas fa-sync-alt me-1"></i>Auto ${getHumanIntervalLabel(refreshMs)}</span>` 
                       : `<span class="badge bg-secondary"><i class="fas fa-pause me-1"></i>Manual</span>`}
            </div>
            <div class="d-flex align-items-center gap-1 table-buttons">
                <button class="btn btn-sm btn-outline-secondary" onclick="refreshReport('${reportKey}')" title="Refresh now">
                    <i class="fas fa-sync-alt"></i>
                </button>
                <button class="btn btn-sm ${auto ? 'btn-warning' : 'btn-success'}" onclick="toggleReportAuto('${reportKey}')" title="${auto ? 'Pause auto-refresh' : 'Resume auto-refresh'}">
                    <i class="fas ${auto ? 'fa-pause' : 'fa-play'}"></i>
                </button>
                <button class="btn btn-sm btn-close btn-close-white" onclick="closeReportCard('${reportKey}')"></button>
            </div>
        </div>
        ${filterSummary ? `<div class="text-muted small mb-2">${filterSummary}</div>` : ''}
        <style>${table_badge_colors}</style>
        <div class="table-responsive summary-table" id="summary-table-${reportKey}">
            <table class="table data-table mb-0 table-bordered">
                ${tableHead}
                ${tableBody}
            </table>
        </div>` : `<div class="alert alert-info py-2 mb-0">No summary data available</div>`;

    return `
        <div class="border-0 shadow-none card mb-3">
            <div class="border-0 shadow-none card-header d-flex justify-content-between align-items-center py-2">
                <h6 class="fw-bold"><i class="fas fa-table me-1"></i>${configName}</h6>
                <button class="btn btn-sm btn-close btn-close-white" onclick="closeReportCard('${reportKey}')"></button>
            </div>
            <div class="border-0 shadow-none card-body p-2">${tableHTML}</div>
        </div>`;
}

// Convert start list API data to HTML
function convertStartListToHTML(apiData, heatNumber, reportKey) {
    const participants = apiData?.participants || [];
    
    let tableHTML = `
        <div class="table-responsive">
            <table class="table table-sm table-bordered mb-0">
                <thead class="table-primary">
                    <tr>
                        <th>Bib</th>
                        <th>Name</th>
                        <th>Category</th>
                        <th>Status</th>
                    </tr>
                </thead>
                <tbody>`;
    
    if (participants.length > 0) {
        participants.forEach(p => {
            tableHTML += `
                <tr>
                    <td><span class="badge bg-primary">${p.bib_number || 'TBD'}</span></td>
                    <td>${p.name || 'Unknown'}</td>
                    <td>${p.category || 'N/A'}</td>
                    <td><span class="badge bg-${p.status === 'confirmed' ? 'success' : 'warning'}">${p.status || 'Pending'}</span></td>
                </tr>`;
        });
    } else {
        tableHTML += '<tr><td colspan="4" class="text-center text-muted">No participants assigned</td></tr>';
    }
    
    tableHTML += `
                </tbody>
            </table>
        </div>`;

    return `
        <div class="border-0 shadow-none card mb-3">
            <div class="border-0 shadow-none card-header d-flex justify-content-between align-items-center py-2">
                <h6 class="fw-bold"><i class="fas fa-users me-1"></i>Heat ${heatNumber} Start List</h6>
                <button class="btn btn-sm btn-close btn-close-white" onclick="closeReportCard('${reportKey}')"></button>
            </div>
            <div class="border-0 shadow-none card-body p-2">${tableHTML}</div>
        </div>`;
}

// FLIP Animation Functions
function getRowRects(reportKey) {
    const container = document.getElementById(`summary-table-${reportKey}`);
    const rows = container ? container.querySelectorAll('tbody tr') : null;
    const rects = {};
    if (!rows) return rects;
    rows.forEach(tr => {
        const key = getRowKeyBySecondColumn(tr);
        if (key) rects[key] = tr.getBoundingClientRect();
    });
    return rects;
}

function playFlipAnimation(reportKey, prevRects) {
    const container = document.getElementById(`summary-table-${reportKey}`);
    if (!container) return;
    const rows = container.querySelectorAll('tbody tr');
    rows.forEach(tr => {
        const key = getRowKeyBySecondColumn(tr);
        if (!key) return;

        const oldRect = prevRects[key];
        const newRect = tr.getBoundingClientRect();

        if (oldRect) {
            const dy = oldRect.top - newRect.top;
            if (Math.abs(dy) > 0.5) {
                tr.style.transition = 'none';
                tr.style.transform = `translateY(${dy}px)`;
                // force reflow
                void tr.offsetHeight;
                tr.style.transition = 'transform 1200ms ease, opacity 1200ms ease';
                tr.style.transform = '';
            }
        } else {
            // New row: fade+slide in
            tr.style.transition = 'none';
            tr.style.opacity = '0';
            tr.style.transform = 'translateY(8px)';
            void tr.offsetHeight;
            tr.style.transition = 'transform 1200ms ease, opacity 1200ms ease';
            tr.style.opacity = '1';
            tr.style.transform = '';
        }

        const cleanup = () => {
            tr.style.transition = '';
            tr.style.transform = '';
            tr.style.opacity = '';
            tr.removeEventListener('transitionend', cleanup);
        };
        tr.addEventListener('transitionend', cleanup);
    });
}

function getRowKeyBySecondColumn(tr) {
    const cells = tr.querySelectorAll('td');
    return cells.length >= 2 ? cells[1].textContent.trim() : null;
}

function buildSummaryRowMaps(reportKey) {
    const container = document.getElementById(`summary-table-${reportKey}`);
    const rows = container ? container.querySelectorAll('tbody tr') : null;
    const indexMap = {};
    const contentMap = {};
    if (!rows) return { indexMap, contentMap };
    let idx = 0;
    rows.forEach(tr => {
        const key = getRowKeyBySecondColumn(tr);
        if (key) {
            indexMap[key] = idx++;
            contentMap[key] = tr.innerHTML;
        }
    });
    return { indexMap, contentMap };
}

function trackAndAnimateSummaryTable(reportKey, prev) {
    const maps = buildSummaryRowMaps(reportKey);
    // Add highlighting for changed rows
    const container = document.getElementById(`summary-table-${reportKey}`);
    if (container && prev.rowContentMap) {
        const rows = container.querySelectorAll('tbody tr');
        rows.forEach(tr => {
            const key = getRowKeyBySecondColumn(tr);
            if (key && prev.rowContentMap[key] && prev.rowContentMap[key] !== tr.innerHTML) {
                tr.classList.add('table-warning');
                setTimeout(() => tr.classList.remove('table-warning'), 3000);
            }
        });
    }
    return maps;
}

// Report control functions
function closeReportCard(reportKey) {
    activeReports.delete(reportKey);
    const parts = reportKey.split('-');
    const eventId = parts[0];
    const heatKey = parts.slice(1, -1).join('-');
    
    let holder;
    if (heatKey === 'all') {
        holder = document.getElementById(`general-report-cards-${eventId}`);
    } else {
        holder = document.getElementById(`report-cards-${eventId}-${heatKey}`);
    }
    
    if (holder) {
        morphHtml(holder, '');
    }
}

function refreshReport(reportKey) {
    const report = activeReports.get(reportKey);
    if (!report) return;
    
    const parts = reportKey.split('-');
    const eventId = parts[0];
    const heatNumber = parts[1] !== 'all' ? parts[1] : null;
    
    if (report.type === 'summary_table') {
        loadSummaryTableCard(eventId, heatNumber, report.configId, report.configName, { refresh: true });
    } else if (report.type === 'start_list') {
        loadStartListCard(eventId, heatNumber);
    }
}

function toggleReportAuto(reportKey) {
    const report = activeReports.get(reportKey);
    if (report) {
        report.auto = !report.auto;
        refreshReport(reportKey); // Refresh to update UI
    }
}

function showReportUpdating(reportKey) {
    const container = document.getElementById(`summary-table-${reportKey}`);
    if (container) {
        const overlay = document.createElement('div');
        overlay.className = 'updating-overlay';
        overlay.innerHTML = '<div class="spinner-border spinner-border-sm"></div>';
        overlay.style.cssText = 'position:absolute;top:0;left:0;right:0;bottom:0;background:rgba(255,255,255,0.8);display:flex;justify-content:center;align-items:center;z-index:10;';
        container.style.position = 'relative';
        container.appendChild(overlay);
        
        setTimeout(() => overlay.remove(), 2000);
    }
}

// Simple morphing function for DOM updates
function morphHtml(element, newHtml) {
    element.innerHTML = newHtml;
}

function getHumanIntervalLabel(ms) {
    if (ms < 60000) return `${ms/1000}s`;
    return `${ms/60000}min`;
}

// Auto-refresh for active reports
setInterval(() => {
    activeReports.forEach((report, reportKey) => {
        if (report.auto !== false && report.type === 'summary_table') {
            const jitter = Math.random() * 5000; // 0-5 second jitter
            setTimeout(() => refreshReport(reportKey), jitter);
        }
    });
}, refreshMs);
