<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>StyleScore Live Dashboard</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
    <style>
        :root {
            --primary-color: #2c3e50;
            --secondary-color: #3498db;
            --success-color: #27ae60;
            --warning-color: #f39c12;
            --danger-color: #e74c3c;
            --dark-color: #34495e;
            --light-bg: #ecf0f1;
        }

        body {
            background: linear-gradient(135deg, var(--light-bg) 0%, #d5dbdb 100%);
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            min-height: 100vh;
        }

        .navbar {
            background: linear-gradient(135deg, var(--primary-color) 0%, var(--dark-color) 100%);
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }

        .main-header {
            background: linear-gradient(135deg, var(--secondary-color) 0%, var(--primary-color) 100%);
            color: white;
            padding: 2rem 0;
            text-align: center;
            margin-bottom: 2rem;
            position: relative;
            overflow: hidden;
        }

        .main-header::before {
            content: '';
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background: url('data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100"><circle cx="50" cy="50" r="2" fill="rgba(255,255,255,0.1)"/></svg>') repeat;
            animation: float 20s infinite linear;
        }

        @keyframes float {
            0% { transform: translateY(0) rotate(0deg); }
            100% { transform: translateY(-100px) rotate(360deg); }
        }

        .section-card {
            background: white;
            border-radius: 15px;
            box-shadow: 0 5px 20px rgba(0,0,0,0.1);
            margin-bottom: 2rem;
            overflow: hidden;
            transition: transform 0.3s ease, box-shadow 0.3s ease;
        }

        .section-card:hover {
            transform: translateY(-5px);
            box-shadow: 0 10px 30px rgba(0,0,0,0.15);
        }

        .section-header {
            background: linear-gradient(45deg, var(--primary-color), var(--dark-color));
            color: white;
            padding: 1rem 1.5rem;
            font-weight: 600;
            display: flex;
            align-items: center;
            gap: 0.5rem;
        }

        .section-content {
            padding: 1.5rem;
        }

        .participant-card {
            background: linear-gradient(135deg, #ffffff 0%, #f8f9fa 100%);
            border: 1px solid #e9ecef;
            border-radius: 10px;
            padding: 1rem;
            margin-bottom: 1rem;
            transition: all 0.3s ease;
            position: relative;
            overflow: hidden;
        }

        .participant-card:hover {
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(0,0,0,0.1);
            border-color: var(--secondary-color);
        }

        .participant-card::before {
            content: '';
            position: absolute;
            top: 0;
            left: 0;
            width: 4px;
            height: 100%;
            background: var(--secondary-color);
            transition: width 0.3s ease;
        }

        .participant-card:hover::before {
            width: 6px;
        }

        .participant-photo {
            width: 60px;
            height: 60px;
            border-radius: 50%;
            object-fit: cover;
            border: 3px solid white;
            box-shadow: 0 2px 10px rgba(0,0,0,0.2);
            margin-right: 1rem;
        }

        .participant-info {
            flex-grow: 1;
        }

        .participant-name {
            font-weight: 600;
            color: var(--primary-color);
            margin-bottom: 0.25rem;
            font-size: 1.1rem;
        }

        .participant-details {
            color: #6c757d;
            font-size: 0.9rem;
            margin-bottom: 0.5rem;
        }

        .score-badge {
            background: linear-gradient(45deg, var(--success-color), #2ecc71);
            color: white;
            padding: 0.5rem 1rem;
            border-radius: 25px;
            font-weight: 600;
            font-size: 1.1rem;
            box-shadow: 0 2px 10px rgba(39, 174, 96, 0.3);
        }

        .heat-info {
            background: linear-gradient(45deg, var(--warning-color), #e67e22);
            color: white;
            padding: 0.3rem 0.8rem;
            border-radius: 15px;
            font-size: 0.85rem;
            font-weight: 500;
        }

        .status-badge {
            padding: 0.25rem 0.75rem;
            border-radius: 15px;
            font-size: 0.8rem;
            font-weight: 500;
            text-transform: uppercase;
        }

        .status-performing {
            background: linear-gradient(45deg, var(--danger-color), #c0392b);
            color: white;
            animation: pulse 2s infinite;
        }

        .status-waiting {
            background: linear-gradient(45deg, var(--warning-color), #e67e22);
            color: white;
        }

        .status-scored {
            background: linear-gradient(45deg, var(--success-color), #2ecc71);
            color: white;
        }

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

        .stats-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 1rem;
            margin-bottom: 2rem;
        }

        .stat-card {
            background: linear-gradient(135deg, white 0%, #f8f9fa 100%);
            border-radius: 10px;
            padding: 1.5rem;
            text-align: center;
            border: 1px solid #e9ecef;
            transition: all 0.3s ease;
        }

        .stat-card:hover {
            transform: translateY(-3px);
            box-shadow: 0 8px 25px rgba(0,0,0,0.1);
        }

        .stat-number {
            font-size: 2rem;
            font-weight: 700;
            color: var(--primary-color);
            margin-bottom: 0.5rem;
        }

        .stat-label {
            color: #6c757d;
            font-size: 0.9rem;
            text-transform: uppercase;
            letter-spacing: 0.5px;
        }

        .loading-spinner {
            display: inline-block;
            width: 20px;
            height: 20px;
            border: 3px solid #f3f3f3;
            border-top: 3px solid var(--secondary-color);
            border-radius: 50%;
            animation: spin 1s linear infinite;
            margin-right: 0.5rem;
        }

        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }

        /* Live Score Viewer Styles */
        #live-scores-content {
            transition: all 0.3s ease;
        }

        #scores-table {
            font-size: 0.9rem;
        }

        #scores-table th {
            font-weight: 600;
            text-transform: uppercase;
            font-size: 0.8rem;
            letter-spacing: 0.5px;
        }

        #scores-table .badge {
            font-size: 0.75rem;
        }

        /* Reports section styles */
        .card {
            transition: transform 0.2s ease, box-shadow 0.2s ease;
        }

        .card:hover {
            transform: translateY(-2px);
            box-shadow: 0 4px 15px rgba(0,0,0,0.1);
        }

        /* Heat details styles */
        .heat-selector-container select {
            font-weight: 500;
        }

        .list-group-item {
            border-left: 4px solid transparent;
            transition: border-left-color 0.2s ease;
        }

        .list-group-item:hover {
            border-left-color: var(--primary-color);
        }

        .last-updated {
            text-align: center;
            color: #6c757d;
            font-size: 0.9rem;
            margin-top: 2rem;
            padding: 1rem;
            background: rgba(255,255,255,0.8);
            border-radius: 10px;
        }

        .error-message {
            background: linear-gradient(45deg, var(--danger-color), #c0392b);
            color: white;
            padding: 1rem;
            border-radius: 10px;
            margin: 1rem 0;
            text-align: center;
        }

        .refresh-button {
            position: fixed;
            bottom: 20px;
            right: 20px;
            background: linear-gradient(45deg, var(--secondary-color), var(--primary-color));
            color: white;
            border: none;
            border-radius: 50%;
            width: 60px;
            height: 60px;
            font-size: 1.5rem;
            box-shadow: 0 4px 20px rgba(0,0,0,0.2);
            cursor: pointer;
            transition: all 0.3s ease;
        }

        .refresh-button:hover {
            transform: scale(1.1);
            box-shadow: 0 6px 25px rgba(0,0,0,0.3);
        }

        @media (max-width: 768px) {
            .participant-card {
                flex-direction: column;
                text-align: center;
            }
            
            .participant-photo {
                margin: 0 auto 1rem auto;
            }
            
            .stats-grid {
                grid-template-columns: repeat(2, 1fr);
            }
        }
    </style>
</head>
<body>
    <nav class="navbar navbar-expand-lg navbar-dark">
        <div class="container">
            <a class="navbar-brand" href="#">
                <i class="fas fa-trophy me-2"></i>StyleScore Live
            </a>
            <div class="navbar-nav ms-auto">
                <span class="navbar-text">
                    <i class="fas fa-circle text-success me-1"></i>
                    Live Updates
                </span>
            </div>
        </div>
    </nav>

    <div class="main-header">
        <div class="container">
            <h1 class="mb-3">
                <i class="fas fa-medal me-3"></i>
                <span id="event-title">StyleScore Competition</span>
            </h1>
            <p class="lead mb-0" id="event-subtitle">Live Results Dashboard</p>
        </div>
    </div>

    <div class="container">
        <!-- Event Statistics -->
        <div class="stats-grid" id="stats-container">
            <div class="stat-card">
                <div class="stat-number" id="participant-count">0</div>
                <div class="stat-label">Participants</div>
            </div>
            <div class="stat-card">
                <div class="stat-number" id="heat-count">0</div>
                <div class="stat-label">Heats</div>
            </div>
            <div class="stat-card">
                <div class="stat-number" id="score-count">0</div>
                <div class="stat-label">Scores</div>
            </div>
            <div class="stat-card">
                <div class="stat-number" id="completion-percentage">0%</div>
                <div class="stat-label">Complete</div>
            </div>
        </div>

        <!-- Latest Score -->
        <div class="section-card" id="latest-score-section">
            <div class="section-header">
                <i class="fas fa-star"></i>
                Latest Score
            </div>
            <div class="section-content" id="latest-score-content">
                <div class="text-center text-muted">
                    <div class="loading-spinner"></div>
                    Loading latest score...
                </div>
            </div>
        </div>

        <!-- Performing Now -->
        <div class="section-card" id="performing-now-section">
            <div class="section-header">
                <i class="fas fa-play-circle"></i>
                Performing Now
            </div>
            <div class="section-content" id="performing-now-content">
                <div class="text-center text-muted">
                    <div class="loading-spinner"></div>
                    Loading current performer...
                </div>
            </div>
        </div>

        <!-- Next on Start -->
        <div class="section-card" id="next-on-start-section">
            <div class="section-header">
                <i class="fas fa-clock"></i>
                Next on Start
            </div>
            <div class="section-content" id="next-on-start-content">
                <div class="text-center text-muted">
                    <div class="loading-spinner"></div>
                    Loading next participant...
                </div>
            </div>
        </div>

        <!-- Heat Information -->
        <div class="section-card" id="heats-section">
            <div class="section-header">
                <i class="fas fa-list"></i>
                Heat Status
            </div>
            <div class="section-content" id="heats-content">
                <div class="text-center text-muted">
                    <div class="loading-spinner"></div>
                    Loading heat information...
                </div>
            </div>
        </div>

        <!-- Live Score Viewer -->
        <div class="section-card" id="live-scores-section">
            <div class="section-header">
                <i class="fas fa-chart-line"></i>
                Live Score Viewer
                <div class="ms-auto">
                    <button class="btn btn-sm btn-light" onclick="dashboard.toggleScoreViewer()">
                        <i class="fas fa-eye" id="score-viewer-toggle"></i>
                    </button>
                </div>
            </div>
            <div class="section-content" id="live-scores-content" style="display: none;">
                <div class="row">
                    <div class="col-md-3">
                        <label class="form-label">Heat:</label>
                        <select class="form-select form-select-sm" id="heat-selector" onchange="dashboard.loadHeatScores()">
                            <option value="">All Heats</option>
                        </select>
                    </div>
                    <div class="col-md-3">
                        <label class="form-label">Category:</label>
                        <select class="form-select form-select-sm" id="category-selector" onchange="dashboard.loadHeatScores()">
                            <option value="">All Categories</option>
                        </select>
                    </div>
                    <div class="col-md-6">
                        <label class="form-label">Actions:</label>
                        <div class="btn-group w-100" role="group">
                            <button class="btn btn-sm btn-outline-primary" onclick="dashboard.refreshScores()">
                                <i class="fas fa-sync-alt"></i> Refresh
                            </button>
                            <button class="btn btn-sm btn-outline-success" onclick="dashboard.exportScores('csv')">
                                <i class="fas fa-download"></i> CSV
                            </button>
                        </div>
                    </div>
                </div>
                <div class="mt-3">
                    <div class="table-responsive">
                        <table class="table table-striped table-hover" id="scores-table">
                            <thead class="table-dark">
                                <tr>
                                    <th>Bib</th>
                                    <th>Name</th>
                                    <th>Category</th>
                                    <th>Heat</th>
                                    <th>Score</th>
                                    <th>Status</th>
                                    <th>Judge</th>
                                    <th>Time</th>
                                </tr>
                            </thead>
                            <tbody id="scores-table-body">
                                <tr>
                                    <td colspan="8" class="text-center text-muted">
                                        <div class="loading-spinner"></div>
                                        Loading scores...
                                    </td>
                                </tr>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>

        <!-- General Reports -->
        <div class="section-card" id="reports-section">
            <div class="section-header">
                <i class="fas fa-file-alt"></i>
                General Reports
            </div>
            <div class="section-content">
                <div class="row">
                    <div class="col-md-6">
                        <div class="card border-0 shadow-sm">
                            <div class="card-body text-center">
                                <i class="fas fa-list-ol fa-2x text-primary mb-3"></i>
                                <h6 class="card-title">Start Lists</h6>
                                <p class="card-text text-muted">View participant start orders and heat assignments</p>
                                <div class="btn-group w-100">
                                    <button class="btn btn-primary btn-sm" onclick="dashboard.viewStartList()">
                                        <i class="fas fa-eye"></i> View
                                    </button>
                                    <button class="btn btn-outline-primary btn-sm" onclick="dashboard.downloadReport('start_list')">
                                        <i class="fas fa-download"></i> Download
                                    </button>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="col-md-6">
                        <div class="card border-0 shadow-sm">
                            <div class="card-body text-center">
                                <i class="fas fa-table fa-2x text-success mb-3"></i>
                                <h6 class="card-title">Summary Tables</h6>
                                <p class="card-text text-muted">Complete results and rankings</p>
                                <div class="btn-group w-100">
                                    <button class="btn btn-success btn-sm" onclick="dashboard.viewSummaryTable()">
                                        <i class="fas fa-eye"></i> View
                                    </button>
                                    <button class="btn btn-outline-success btn-sm" onclick="dashboard.downloadReport('summary_table')">
                                        <i class="fas fa-download"></i> Download
                                    </button>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Heat Details -->
        <div class="section-card" id="heat-details-section">
            <div class="section-header">
                <i class="fas fa-layer-group"></i>
                Heat Details
            </div>
            <div class="section-content">
                <div class="heat-selector-container mb-3">
                    <select class="form-select" id="heat-detail-selector" onchange="dashboard.loadHeatDetails()">
                        <option value="">Select Heat to View Details</option>
                    </select>
                </div>
                <div id="heat-details-content">
                    <div class="text-center text-muted">
                        <i class="fas fa-info-circle fa-2x mb-3"></i>
                        <p>Select a heat from the dropdown above to view detailed information</p>
                    </div>
                </div>
            </div>
        </div>

        <!-- Last Updated -->
        <div class="last-updated" id="last-updated">
            <i class="fas fa-sync-alt me-2"></i>
            Loading data...
        </div>
    </div>

    <!-- Refresh Button -->
    <button class="refresh-button" onclick="loadData()" title="Refresh Data">
        <i class="fas fa-sync-alt"></i>
    </button>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        class StyleScoreDashboard {
            constructor() {
                this.eventData = null;
                this.latestData = null;
                this.heatsData = null;
                this.scoresData = null;
                this.lastUpdate = null;
                this.refreshInterval = 10000; // 10 seconds
                this.autoRefreshTimer = null;
                this.pinnedCards = new Set();
                this.cardZIndex = 1000;
            }

            async init() {
                console.log('Initializing StyleScore Dashboard');
                await this.loadData();
                this.startAutoRefresh();
            }

            async loadData() {
                try {
                    console.log('Loading dashboard data...');
                    
                    // Load all data files
                    const [eventResponse, latestResponse, heatsResponse, scoresResponse] = await Promise.all([
                        fetch('data_overview.json'),
                        fetch('data_latest.json'), 
                        fetch('data_heats.json'),
                        fetch('data_scores.json').catch(() => ({ ok: false }))
                    ]);

                    if (!eventResponse.ok || !latestResponse.ok || !heatsResponse.ok) {
                        throw new Error('Failed to load data files');
                    }

                    this.eventData = await eventResponse.json();
                    this.latestData = await latestResponse.json();
                    this.heatsData = await heatsResponse.json();
                    
                    // Scores data is optional
                    if (scoresResponse.ok) {
                        this.scoresData = await scoresResponse.json();
                    }
                    
                    this.lastUpdate = new Date();

                    this.renderDashboard();
                    this.updateLastUpdatedTime();

                } catch (error) {
                    console.error('Error loading data:', error);
                    this.showError('Failed to load live data. Please check your connection.');
                }
            }

            renderDashboard() {
                this.renderEventInfo();
                this.renderStats();
                this.renderLatestScore();
                this.renderPerformingNow();
                this.renderNextOnStart();
                this.renderHeats();
                this.loadHeatDetails(); // Initialize heat details selector
            }

            renderEventInfo() {
                if (this.eventData && this.eventData.event) {
                    document.getElementById('event-title').textContent = this.eventData.event.name || 'StyleScore Competition';
                    document.getElementById('event-subtitle').textContent = 
                        `${this.eventData.event.location || ''} • ${this.eventData.event.sport_discipline || 'Competition'}`;
                }
            }

            renderStats() {
                if (this.eventData) {
                    document.getElementById('participant-count').textContent = this.eventData.participant_count || 0;
                    document.getElementById('heat-count').textContent = this.eventData.heat_count || 0;
                    document.getElementById('score-count').textContent = this.eventData.score_count || 0;
                    
                    // Calculate completion percentage
                    const participantCount = this.eventData.participant_count || 0;
                    const scoreCount = this.eventData.score_count || 0;
                    const completion = participantCount > 0 ? Math.round((scoreCount / participantCount) * 100) : 0;
                    document.getElementById('completion-percentage').textContent = completion + '%';
                }
            }

            renderLatestScore() {
                const container = document.getElementById('latest-score-content');
                
                if (this.latestData && this.latestData.latest_score) {
                    const score = this.latestData.latest_score;
                    container.innerHTML = this.createParticipantCard(score, 'scored');
                } else {
                    container.innerHTML = '<div class="text-center text-muted">No recent scores available</div>';
                }
            }

            renderPerformingNow() {
                const container = document.getElementById('performing-now-content');
                
                if (this.latestData && this.latestData.performing_now) {
                    const performer = this.latestData.performing_now;
                    container.innerHTML = this.createParticipantCard(performer, 'performing');
                } else {
                    container.innerHTML = '<div class="text-center text-muted">No one currently performing</div>';
                }
            }

            renderNextOnStart() {
                const container = document.getElementById('next-on-start-content');
                
                if (this.latestData && this.latestData.next_on_start) {
                    const next = this.latestData.next_on_start;
                    container.innerHTML = this.createParticipantCard(next, 'waiting');
                } else {
                    container.innerHTML = '<div class="text-center text-muted">No upcoming participants</div>';
                }
            }

            renderHeats() {
                const container = document.getElementById('heats-content');
                
                if (this.heatsData && this.heatsData.heats) {
                    // Handle both array format (old) and object format (new API structure)
                    let heatsArray = [];
                    if (Array.isArray(this.heatsData.heats)) {
                        heatsArray = this.heatsData.heats;
                    } else {
                        // Convert object to array, sorting by heat number
                        heatsArray = Object.values(this.heatsData.heats).sort((a, b) => a.heat_number - b.heat_number);
                    }
                    
                    if (heatsArray.length > 0) {
                        const heatsHtml = heatsArray.map(heat => {
                            const participants = heat.participants || 0;
                            const totalScores = heat.total_scores || 0;
                            const completion = participants > 0 ? 
                                Math.round((totalScores / participants) * 100) : 0;
                            
                            return `
                                <div class="d-flex justify-content-between align-items-center p-3 border-bottom">
                                    <div>
                                        <h6 class="mb-1">Heat ${heat.heat_number}</h6>
                                        <small class="text-muted">${heat.heat_name || `Heat ${heat.heat_number}`}</small>
                                        <br><small class="text-muted">${participants} participants</small>
                                    </div>
                                    <div class="text-end">
                                        <div class="progress mb-1" style="width: 100px; height: 8px;">
                                            <div class="progress-bar ${heat.is_active ? 'bg-success' : ''}" style="width: ${completion}%"></div>
                                        </div>
                                        <small class="text-muted">${completion}% complete</small>
                                        ${heat.is_active ? '<small class="text-success d-block">● Active</small>' : ''}
                                    </div>
                                </div>
                            `;
                        }).join('');
                        
                        container.innerHTML = heatsHtml;
                    } else {
                        container.innerHTML = '<div class="text-center text-muted">No heats configured</div>';
                    }
                } else {
                    container.innerHTML = '<div class="text-center text-muted">No heat information available</div>';
                }
            }

            createParticipantCard(participant, status) {
                if (!participant) return '';

                const statusClass = `status-${status}`;
                const statusText = status === 'performing' ? 'Performing' : 
                                status === 'waiting' ? 'Waiting' : 'Latest Score';

                // Create a placeholder image URL using a service or simple colored div
                const placeholderSvg = this.createPlaceholderSvg();
                const photoUrl = participant.photo ? `photos/${participant.photo}` : placeholderSvg;

                const score = participant.score_value ? 
                    `<div class="score-badge">${participant.score_value}</div>` : '';

                return `
                    <div class="participant-card d-flex align-items-center">
                        <img src="${photoUrl}" 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; width: 60px; height: 60px; border-radius: 50%; background: linear-gradient(45deg, #ddd, #f0f0f0); align-items: center; justify-content: center; margin-right: 1rem; color: #999; font-size: 0.8rem; border: 3px solid white; box-shadow: 0 2px 10px rgba(0,0,0,0.2);">
                            <i class="fas fa-user"></i>
                        </div>
                        <div class="participant-info">
                            <div class="participant-name">${participant.first_name || ''} ${participant.last_name || ''}</div>
                            <div class="participant-details">
                                ${participant.club || ''} • ${participant.country || ''}
                                ${participant.category ? `• ${participant.category}` : ''}
                            </div>
                            <div class="d-flex align-items-center gap-2 mt-2">
                                <span class="status-badge ${statusClass}">${statusText}</span>
                                ${participant.heat_number ? `<span class="heat-info">Heat ${participant.heat_number}</span>` : ''}
                                ${participant.bib_number ? `<span class="badge bg-secondary">Bib ${participant.bib_number}</span>` : ''}
                            </div>
                        </div>
                        ${score}
                    </div>
                `;
            }

            createPlaceholderSvg() {
                // Create a simple data URL for placeholder
                const svg = `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100">
                    <circle cx="50" cy="50" r="40" fill="#ddd"/>
                    <text x="50" y="55" text-anchor="middle" fill="#999" font-size="12">No Photo</text>
                </svg>`;
                return 'data:image/svg+xml;base64,' + btoa(svg);
            }

            updateLastUpdatedTime() {
                const container = document.getElementById('last-updated');
                if (this.lastUpdate) {
                    const timeString = this.lastUpdate.toLocaleTimeString();
                    container.innerHTML = `
                        <i class="fas fa-sync-alt me-2"></i>
                        Last updated: ${timeString}
                    `;
                }
            }

            showError(message) {
                const sections = ['latest-score-content', 'performing-now-content', 'next-on-start-content', 'heats-content'];
                sections.forEach(sectionId => {
                    const element = document.getElementById(sectionId);
                    if (element) {
                        element.innerHTML = `<div class="error-message">${message}</div>`;
                    }
                });
            }

            startAutoRefresh() {
                this.autoRefreshTimer = setInterval(() => {
                    this.loadData();
                }, this.refreshInterval);
            }

            stopAutoRefresh() {
                if (this.autoRefreshTimer) {
                    clearInterval(this.autoRefreshTimer);
                    this.autoRefreshTimer = null;
                }
            }

            // Live Score Viewer Methods
            toggleScoreViewer() {
                const content = document.getElementById('live-scores-content');
                const icon = document.getElementById('score-viewer-toggle');
                
                if (content.style.display === 'none') {
                    content.style.display = 'block';
                    icon.className = 'fas fa-eye-slash';
                    this.loadScoreViewerData();
                } else {
                    content.style.display = 'none';
                    icon.className = 'fas fa-eye';
                }
            }

            loadScoreViewerData() {
                this.populateHeatSelector();
                this.populateCategorySelector();
                this.loadHeatScores();
            }

            populateHeatSelector() {
                const selector = document.getElementById('heat-selector');
                selector.innerHTML = '<option value="">All Heats</option>';
                
                if (this.heatsData && this.heatsData.heats) {
                    // Handle both array and object formats
                    let heatsArray = [];
                    if (Array.isArray(this.heatsData.heats)) {
                        heatsArray = this.heatsData.heats;
                    } else {
                        // Convert object to array
                        heatsArray = Object.values(this.heatsData.heats);
                    }
                    
                    heatsArray.forEach(heat => {
                        const option = document.createElement('option');
                        option.value = heat.heat_number || heat.id;
                        option.textContent = `Heat ${heat.heat_number} - ${heat.heat_name || heat.category_name || 'Unknown'}`;
                        selector.appendChild(option);
                    });
                }
            }

            populateCategorySelector() {
                const selector = document.getElementById('category-selector');
                selector.innerHTML = '<option value="">All Categories</option>';
                
                if (this.heatsData && this.heatsData.heats) {
                    // Handle both array and object formats
                    let heatsArray = [];
                    if (Array.isArray(this.heatsData.heats)) {
                        heatsArray = this.heatsData.heats;
                    } else {
                        // Convert object to array
                        heatsArray = Object.values(this.heatsData.heats);
                    }
                    
                    const categories = [...new Set(heatsArray.map(h => h.heat_name || h.category_name || 'Unknown'))];
                    categories.forEach(category => {
                        const option = document.createElement('option');
                        option.value = category;
                        option.textContent = category;
                        selector.appendChild(option);
                    });
                }
            }

            async loadHeatScores() {
                const tbody = document.getElementById('scores-table-body');
                tbody.innerHTML = '<tr><td colspan="8" class="text-center"><div class="loading-spinner"></div> Loading scores...</td></tr>';

                try {
                    const response = await fetch('data_scores.json');
                    if (response.ok) {
                        const scoresData = await response.json();
                        this.renderScoresTable(scoresData);
                    } else {
                        tbody.innerHTML = '<tr><td colspan="8" class="text-center text-muted">No score data available</td></tr>';
                    }
                } catch (error) {
                    console.error('Error loading scores:', error);
                    tbody.innerHTML = '<tr><td colspan="8" class="text-center text-danger">Error loading scores</td></tr>';
                }
            }

            renderScoresTable(scoresData) {
                const tbody = document.getElementById('scores-table-body');
                const heatFilter = document.getElementById('heat-selector').value;
                const categoryFilter = document.getElementById('category-selector').value;

                if (!scoresData || !scoresData.scores || scoresData.scores.length === 0) {
                    tbody.innerHTML = '<tr><td colspan="8" class="text-center text-muted">No scores available</td></tr>';
                    return;
                }

                let filteredScores = scoresData.scores;

                // Apply filters
                if (heatFilter) {
                    filteredScores = filteredScores.filter(score => score.heat_id == heatFilter);
                }
                if (categoryFilter) {
                    filteredScores = filteredScores.filter(score => score.category_name === categoryFilter);
                }

                if (filteredScores.length === 0) {
                    tbody.innerHTML = '<tr><td colspan="8" class="text-center text-muted">No scores match the selected filters</td></tr>';
                    return;
                }

                tbody.innerHTML = '';
                filteredScores.forEach(score => {
                    const row = document.createElement('tr');
                    const statusClass = score.status === 'completed' ? 'text-success' : 
                                       score.status === 'in_progress' ? 'text-warning' : 'text-muted';
                    
                    const participantName = `${score.first_name || ''} ${score.last_name || ''}`.trim() || score.participant_name || 'Unknown';
                    
                    row.innerHTML = `
                        <td><span class="badge bg-primary">${score.bib_number || 'N/A'}</span></td>
                        <td>${participantName}</td>
                        <td>${score.category || score.category_name || 'N/A'}</td>
                        <td>Heat ${score.heat_number || 'N/A'}</td>
                        <td><strong>${score.score_value || '0.00'}</strong></td>
                        <td><span class="badge ${statusClass === 'text-success' ? 'bg-success' : statusClass === 'text-warning' ? 'bg-warning' : 'bg-secondary'}">${score.status || 'pending'}</span></td>
                        <td>${score.judge_name || 'N/A'}</td>
                        <td><small>${score.score_time ? new Date(score.score_time).toLocaleTimeString() : 'N/A'}</small></td>
                    `;
                    tbody.appendChild(row);
                });
            }

            refreshScores() {
                this.loadHeatScores();
            }

            exportScores(format) {
                // Basic CSV export functionality
                if (format === 'csv') {
                    const table = document.getElementById('scores-table');
                    let csv = '';
                    
                    // Headers
                    const headers = Array.from(table.querySelectorAll('thead th')).map(th => th.textContent);
                    csv += headers.join(',') + '\n';
                    
                    // Data rows
                    const rows = Array.from(table.querySelectorAll('tbody tr'));
                    rows.forEach(row => {
                        const cells = Array.from(row.querySelectorAll('td')).map(td => {
                            return '"' + td.textContent.trim().replace(/"/g, '""') + '"';
                        });
                        csv += cells.join(',') + '\n';
                    });
                    
                    // Download
                    const blob = new Blob([csv], { type: 'text/csv' });
                    const url = window.URL.createObjectURL(blob);
                    const a = document.createElement('a');
                    a.href = url;
                    a.download = `scores_${new Date().toISOString().split('T')[0]}.csv`;
                    a.click();
                    window.URL.revokeObjectURL(url);
                }
            }

            // Reports Methods
            viewStartList() {
                this.openReportModal('Start List', this.generateStartListHTML());
            }

            viewSummaryTable() {
                this.openReportModal('Summary Table', this.generateSummaryTableHTML());
            }

            generateStartListHTML() {
                if (!this.heatsData || !this.heatsData.heats) {
                    return '<p class="text-muted">No heat data available</p>';
                }

                let html = '<div class="table-responsive"><table class="table table-striped">';
                html += '<thead class="table-dark"><tr><th>Heat</th><th>Bib</th><th>Name</th><th>Category</th><th>Status</th></tr></thead><tbody>';

                // Handle both array and object formats
                let heatsArray = [];
                if (Array.isArray(this.heatsData.heats)) {
                    heatsArray = this.heatsData.heats;
                } else {
                    // Convert object to array
                    heatsArray = Object.values(this.heatsData.heats);
                }

                heatsArray.forEach(heat => {
                    if (heat.participants && heat.participants.length > 0) {
                        heat.participants.forEach(participant => {
                            html += `
                                <tr>
                                    <td>Heat ${heat.heat_number}</td>
                                    <td><span class="badge bg-primary">${participant.bib_number || 'TBD'}</span></td>
                                    <td>${participant.name}</td>
                                    <td>${heat.category_name || heat.heat_name}</td>
                                    <td><span class="badge ${heat.status === 'completed' ? 'bg-success' : heat.status === 'active' ? 'bg-warning' : 'bg-secondary'}">${heat.status}</span></td>
                                </tr>
                            `;
                        });
                    }
                });

                html += '</tbody></table></div>';
                return html;
            }

            generateSummaryTableHTML() {
                if (!this.scoresData || !this.scoresData.scores) {
                    return '<p class="text-muted">No scoring data available</p>';
                }

                // Group scores by category and calculate rankings
                const categories = {};
                this.scoresData.scores.forEach(score => {
                    const categoryName = score.category || score.category_name || 'Uncategorized';
                    if (!categories[categoryName]) {
                        categories[categoryName] = [];
                    }
                    categories[categoryName].push(score);
                });

                let html = '';
                Object.keys(categories).forEach(categoryName => {
                    const categoryScores = categories[categoryName]
                        .filter(score => score.score_value > 0)
                        .sort((a, b) => parseFloat(b.score_value) - parseFloat(a.score_value));

                    html += `<h5 class="mt-4">${categoryName}</h5>`;
                    html += '<div class="table-responsive"><table class="table table-striped">';
                    html += '<thead class="table-dark"><tr><th>Rank</th><th>Bib</th><th>Name</th><th>Score</th><th>Heat</th></tr></thead><tbody>';

                    categoryScores.forEach((score, index) => {
                        const rankClass = index === 0 ? 'text-warning' : index === 1 ? 'text-secondary' : index === 2 ? 'text-dark' : '';
                        const participantName = `${score.first_name || ''} ${score.last_name || ''}`.trim() || score.participant_name || 'Unknown';
                        
                        html += `
                            <tr>
                                <td><strong class="${rankClass}">${index + 1}</strong></td>
                                <td><span class="badge bg-primary">${score.bib_number || 'N/A'}</span></td>
                                <td>${participantName}</td>
                                <td><strong>${score.score_value}</strong></td>
                                <td>${score.heat_name || `Heat ${score.heat_number}` || 'N/A'}</td>
                            </tr>
                        `;
                    });

                    html += '</tbody></table></div>';
                });

                return html || '<p class="text-muted">No completed scores available</p>';
            }

            openReportModal(title, content) {
                // Create modal if it doesn't exist
                let modal = document.getElementById('reportModal');
                if (!modal) {
                    modal = document.createElement('div');
                    modal.id = 'reportModal';
                    modal.className = 'modal fade';
                    modal.innerHTML = `
                        <div class="modal-dialog modal-lg">
                            <div class="modal-content">
                                <div class="modal-header">
                                    <h5 class="modal-title" id="reportModalTitle"></h5>
                                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                                </div>
                                <div class="modal-body" id="reportModalBody"></div>
                                <div class="modal-footer">
                                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
                                    <button type="button" class="btn btn-primary" onclick="dashboard.printReport()">Print</button>
                                </div>
                            </div>
                        </div>
                    `;
                    document.body.appendChild(modal);
                }

                document.getElementById('reportModalTitle').textContent = title;
                document.getElementById('reportModalBody').innerHTML = content;
                
                const bootstrapModal = new bootstrap.Modal(modal);
                bootstrapModal.show();
            }

            downloadReport(type) {
                let content, filename;
                
                if (type === 'start_list') {
                    content = this.generateStartListHTML();
                    filename = `start_list_${new Date().toISOString().split('T')[0]}.html`;
                } else if (type === 'summary_table') {
                    content = this.generateSummaryTableHTML();
                    filename = `summary_table_${new Date().toISOString().split('T')[0]}.html`;
                }

                const fullHTML = `
                    <!DOCTYPE html>
                    <html>
                    <head>
                        <title>${type.replace('_', ' ').toUpperCase()}</title>
                        <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
                        <style>
                            body { padding: 20px; }
                            @media print { .no-print { display: none; } }
                        </style>
                    </head>
                    <body>
                        <div class="container">
                            <h2>${type.replace('_', ' ').toUpperCase()}</h2>
                            <p class="text-muted">Generated: ${new Date().toLocaleString()}</p>
                            ${content}
                        </div>
                    </body>
                    </html>
                `;

                const blob = new Blob([fullHTML], { type: 'text/html' });
                const url = window.URL.createObjectURL(blob);
                const a = document.createElement('a');
                a.href = url;
                a.download = filename;
                a.click();
                window.URL.revokeObjectURL(url);
            }

            printReport() {
                window.print();
            }

            // Heat Details Methods
            loadHeatDetails() {
                const selector = document.getElementById('heat-detail-selector');
                const content = document.getElementById('heat-details-content');
                
                // Populate selector if empty
                if (selector.children.length === 1) {
                    if (this.heatsData && this.heatsData.heats) {
                        // Handle both array and object formats
                        let heatsArray = [];
                        if (Array.isArray(this.heatsData.heats)) {
                            heatsArray = this.heatsData.heats;
                        } else {
                            heatsArray = Object.values(this.heatsData.heats).sort((a, b) => a.heat_number - b.heat_number);
                        }
                        
                        heatsArray.forEach(heat => {
                            const option = document.createElement('option');
                            option.value = heat.heat_number;
                            option.textContent = `Heat ${heat.heat_number} - ${heat.heat_name || `Heat ${heat.heat_number}`} (${heat.participants || 0} participants)`;
                            selector.appendChild(option);
                        });
                    }
                }

                const selectedHeatNumber = selector.value;
                if (!selectedHeatNumber) {
                    content.innerHTML = `
                        <div class="text-center text-muted">
                            <i class="fas fa-info-circle fa-2x mb-3"></i>
                            <p>Select a heat from the dropdown above to view detailed information</p>
                        </div>
                    `;
                    return;
                }

                // Find heat by heat_number - handle both array and object formats
                let heat = null;
                if (Array.isArray(this.heatsData.heats)) {
                    heat = this.heatsData.heats.find(h => h.heat_number == selectedHeatNumber);
                } else {
                    // Object format - try direct key access first, then find by heat_number
                    heat = this.heatsData.heats[selectedHeatNumber];
                    if (!heat) {
                        // Fallback: convert to array and find
                        const heatsArray = Object.values(this.heatsData.heats);
                        heat = heatsArray.find(h => h.heat_number == selectedHeatNumber);
                    }
                }
                
                if (!heat) {
                    content.innerHTML = '<div class="alert alert-warning">Heat not found</div>';
                    return;
                }

                this.renderHeatDetails(heat, content);
            }

            renderHeatDetails(heat, container) {
                const isActive = heat.is_active;
                const statusClass = isActive ? 'success' : 'secondary';
                const statusText = isActive ? 'Active' : 'Inactive';

                let html = `
                    <div class="row">
                        <div class="col-md-6">
                            <div class="card border-${statusClass}">
                                <div class="card-header bg-${statusClass} text-white">
                                    <h6 class="mb-0"><i class="fas fa-info-circle"></i> Heat Information</h6>
                                </div>
                                <div class="card-body">
                                    <p><strong>Heat Number:</strong> ${heat.heat_number}</p>
                                    <p><strong>Heat Name:</strong> ${heat.heat_name || `Heat ${heat.heat_number}`}</p>
                                    <p><strong>Status:</strong> <span class="badge bg-${statusClass}">${statusText}</span></p>
                                    <p><strong>Participants:</strong> ${heat.participants || 0}</p>
                                    <p><strong>Total Scores:</strong> ${heat.total_scores || 0}</p>
                                    ${heat.scoring_type ? `<p><strong>Scoring Type:</strong> ${heat.scoring_type}</p>` : ''}
                                    ${heat.runs_count ? `<p><strong>Runs per Participant:</strong> ${heat.runs_count}</p>` : ''}
                                </div>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="card">
                                <div class="card-header">
                                    <h6 class="mb-0"><i class="fas fa-users"></i> Current Status</h6>
                                </div>
                                <div class="card-body">
                `;

                // Show current heat status information
                if (isActive) {
                    html += '<div class="alert alert-success"><i class="fas fa-play"></i> This heat is currently active</div>';
                    
                    if (heat.bib_performing) {
                        html += `<p><strong>Currently Performing:</strong> BIB ${heat.bib_performing}</p>`;
                    }
                    if (heat.bib_on_start && heat.bib_start_name) {
                        html += `<p><strong>On Start:</strong> BIB ${heat.bib_on_start} - ${heat.bib_start_name}</p>`;
                    }
                    if (heat.bib_latest_on_run && heat.bib_latest_name) {
                        html += `<p><strong>Latest Score:</strong> BIB ${heat.bib_latest_on_run} - ${heat.bib_latest_name}</p>`;
                    }
                } else {
                    html += '<div class="alert alert-secondary"><i class="fas fa-pause"></i> This heat is not currently active</div>';
                }

                // Show completion percentage
                const participants = heat.participants || 0;
                const totalScores = heat.total_scores || 0;
                const completion = participants > 0 ? Math.round((totalScores / participants) * 100) : 0;
                
                html += `
                    <div class="mt-3">
                        <p><strong>Completion Progress:</strong></p>
                        <div class="progress mb-2">
                            <div class="progress-bar bg-${statusClass}" style="width: ${completion}%"></div>
                        </div>
                        <small class="text-muted">${completion}% complete (${totalScores} of ${participants} expected scores)</small>
                    </div>
                `;

                html += `
                                </div>
                            </div>
                        </div>
                    </div>
                `;

                container.innerHTML = html;
            }
        }

        // Global functions for external access
        let dashboard;

        function loadData() {
            if (dashboard) {
                dashboard.loadData();
            }
        }

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

        // Handle page visibility changes to pause/resume updates
        document.addEventListener('visibilitychange', function() {
            if (dashboard) {
                if (document.hidden) {
                    dashboard.stopAutoRefresh();
                } else {
                    dashboard.startAutoRefresh();
                    dashboard.loadData(); // Immediate refresh when page becomes visible
                }
            }
        });
    </script>
</body>
</html>
