<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>Fixtures Overlay</title>
    <script src="qrc:///qtwebchannel/qwebchannel.js"></script>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        
        body {
            font-family: 'Arial', sans-serif;
            background: transparent !important;
            background-color: transparent !important;
            overflow: hidden;
            width: 100vw;
            height: 100vh;
            position: relative;
        }
        
        /* Debug indicator to verify CSS is loaded */
        body::before {
            content: 'Fixtures Overlay v1.0 loaded';
            position: absolute;
            top: 5px;
            left: 5px;
            color: rgba(255,255,255,0.5);
            font-size: 10px;
            z-index: 9999;
        }

        /* Debug console overlay */
        #debugConsole {
            position: absolute;
            top: 10px;
            right: 10px;
            width: 400px;
            height: 300px;
            background: rgba(0, 0, 0, 0.9);
            border: 2px solid #00ff00;
            border-radius: 8px;
            color: #00ff00;
            font-family: 'Courier New', monospace;
            font-size: 11px;
            padding: 8px;
            overflow-y: auto;
            z-index: 10000;
            display: none; /* Hidden by default, shown when --debug-player */
        }

        #debugConsole.show {
            display: block;
        }

        #debugConsole .console-header {
            font-weight: bold;
            border-bottom: 1px solid #00ff00;
            padding-bottom: 4px;
            margin-bottom: 4px;
        }

        #debugConsole .console-message {
            margin: 2px 0;
            word-wrap: break-word;
        }

        #debugConsole .console-timestamp {
            color: #ffff00;
        }

        #debugConsole .console-level-log {
            color: #ffffff;
        }

        #debugConsole .console-level-error {
            color: #ff4444;
        }

        #debugConsole .console-level-warn {
            color: #ffaa00;
        }

        #debugConsole .console-level-info {
            color: #00aaff;
        }
        
        .overlay-container {
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            pointer-events: none;
            z-index: 1000;
            display: flex;
            align-items: center;
            justify-content: center;
        }
        
        .fixtures-panel {
            background: rgba(0, 123, 255, 0.85);
            border-radius: 20px;
            padding: 30px;
            max-width: 90%;
            max-height: 85%; /* Increased from 80% to allow more space */
            overflow: visible; /* Changed from overflow-y: auto to visible to prevent scrollbar */
            box-shadow: 0 8px 32px rgba(0, 0, 0, 0.3);
            backdrop-filter: blur(10px);
            border: 2px solid rgba(255, 255, 255, 0.1);
            opacity: 0;
            animation: fadeInScale 1s ease-out forwards;
            padding-bottom: 50px; /* Add extra bottom padding to ensure content doesn't touch border */
        }
        
        .fixtures-title {
            color: white;
            font-size: 56px;
            font-weight: bold;
            text-align: center;
            margin-bottom: 25px;
            text-shadow: 2px 2px 4px rgba(0, 0, 0, 0.5);
        }
        
        .fixtures-table {
            width: 100%;
            border-collapse: collapse;
            color: white;
            font-size: 32px;
            background: transparent;
        }
        
        .fixtures-table th {
            padding: 8px 4px;
            text-align: center;
            background: rgba(255, 255, 255, 0.1);
            font-weight: bold;
            font-size: 22px;
            text-transform: uppercase;
            letter-spacing: 1px;
            border-radius: 8px;
            margin: 2px;
            text-shadow: 1px 1px 2px rgba(0, 0, 0, 0.5);
        }
        
        .fixtures-table td {
            padding: 8px 6px;
            text-align: center;
            background: rgba(255, 255, 255, 0.05);
            border-radius: 6px;
            margin: 1px;
            transition: background-color 0.3s ease;
        }
        
        .fixtures-table tbody tr:hover td {
            background: rgba(255, 255, 255, 0.15);
        }

        .next-match-info {
            text-align: center;
            color: rgba(255, 255, 255, 0.9);
            font-size: 32px;
            margin-bottom: 10px;
            font-weight: bold;
            text-shadow: 1px 1px 2px rgba(0, 0, 0, 0.5);
        }

        .countdown-timer {
            text-align: center;
            color: #ffeb3b;
            font-size: 48px;
            font-weight: bold;
            margin-bottom: 15px;
            text-shadow: 2px 2px 4px rgba(0, 0, 0, 0.8);
            background: rgba(0, 0, 0, 0.3);
            padding: 8px 16px;
            border-radius: 10px;
            border: 2px solid rgba(255, 235, 59, 0.3);
        }

        .countdown-timer.warning {
            color: #ff9800;
            border-color: rgba(255, 152, 0, 0.5);
        }

        .countdown-timer.urgent {
            color: #f44336;
            border-color: rgba(244, 67, 54, 0.5);
            animation: pulse 1s infinite;
        }

        @keyframes pulse {
            0% { transform: scale(1); }
            50% { transform: scale(1.05); }
            100% { transform: scale(1); }
        }
        
        .match-info {
            font-weight: bold;
            color: #ffffff;
        }
        
        .fighter-names {
            font-size: 28px;
            color: #e6f3ff;
        }

        .venue-info {
            font-size: 26px;
            color: #ccddff;
            font-style: italic;
        }
        
        .odds-value {
            background: rgba(255, 255, 255, 0.2);
            border-radius: 4px;
            padding: 4px 8px;
            font-weight: bold;
            color: #ffffff;
            border: 1px solid rgba(255, 255, 255, 0.2);
            transition: all 0.3s ease;
        }
        
        .odds-value:hover {
            background: rgba(255, 255, 255, 0.3);
            transform: scale(1.05);
        }
        
        .under-over {
            background: rgba(40, 167, 69, 0.3);
            border-color: rgba(40, 167, 69, 0.5);
        }
        
        .loading-message {
            text-align: center;
            color: white;
            font-size: 36px;
            padding: 40px;
        }

        .no-matches {
            text-align: center;
            color: rgba(255, 255, 255, 0.8);
            font-size: 32px;
            padding: 30px;
            font-style: italic;
        }

        .fixture-info {
            text-align: center;
            color: rgba(255, 255, 255, 0.9);
            font-size: 28px;
            margin-bottom: 20px;
            font-style: italic;
        }
        
        /* Animations */
        @keyframes fadeInScale {
            0% {
                opacity: 0;
                transform: scale(0.8);
            }
            100% {
                opacity: 1;
                transform: scale(1);
            }
        }
        
        /* Responsive Design */
        @media (max-width: 1200px) {
            .fixtures-panel {
                padding: 20px;
                max-width: 95%;
            }
            
            .fixtures-title {
                font-size: 48px;
            }

            .fixtures-table {
                font-size: 28px;
            }
            
            .fixtures-table th,
            .fixtures-table td {
                padding: 8px 6px;
            }
        }
        
        @media (max-width: 800px) {
            .fixtures-panel {
                padding: 15px;
                max-width: 98%;
                max-height: 90%;
            }
            
            .fixtures-title {
                font-size: 40px;
                margin-bottom: 15px;
            }

            .fixtures-table {
                font-size: 24px;
            }

            .fixtures-table th,
            .fixtures-table td {
                padding: 6px 4px;
            }

            .odds-value {
                padding: 2px 4px;
                font-size: 22px;
            }
        }
        
    </style>
</head>
<body>
    <!-- Debug Console Overlay -->
    <div id="debugConsole">
        <div class="console-header">🔍 JavaScript Debug Console</div>
        <div id="consoleOutput"></div>
    </div>

    <div class="overlay-container">
        <div class="fixtures-panel" id="fixturesPanel">
            <div class="fixtures-title">Next 5 matches:</div>
            <div class="next-match-info" id="nextMatchInfo" style="display: none;"></div>
            <div class="countdown-timer" id="countdownTimer" style="display: none;"></div>
            <div class="loading-message" id="loadingMessage" style="display: none;">Loading fixture data...</div>
            <div id="fixturesContent" style="display: none;">
                <table class="fixtures-table" id="fixturesTable">
                    <thead>
                        <tr id="tableHeader">
                            <th>Match</th>
                            <th>Fighters</th>
                            <th>Venue</th>
                            <th>WIN1</th>
                            <th>X</th>
                            <th>WIN2</th>
                            <th>UNDER</th>
                            <th>OVER</th>
                        </tr>
                    </thead>
                    <tbody id="tableBody">
                        <!-- Content will be populated by JavaScript -->
                    </tbody>
                </table>
            </div>
            <div class="no-matches" id="noMatches" style="display: none;">
                No matches available for today's fixture
            </div>
        </div>
    </div>

    <script>
        // Global variables for overlay data handling
        let overlayData = {};
        let fixturesData = null;
        let outcomesData = null;
        let countdownInterval = null;
        let nextMatchStartTime = null;
        let startTime = null;

        // Apply console.log override immediately with buffering
        (function() {
            var originalConsoleLog = console.log;
            var messageBuffer = [];

            console.log = function(...args) {
                var message = args.map(String).join(' ');
                if (window.overlay && window.overlay.log) {
                    window.overlay.log('[LOG] ' + message);
                } else {
                    messageBuffer.push('[LOG] ' + message);
                }
                originalConsoleLog.apply(console, args);
            };

            // Function to flush buffer when overlay becomes available
            window.flushConsoleBuffer = function() {
                if (window.overlay && window.overlay.log) {
                    messageBuffer.forEach(function(msg) {
                        window.overlay.log(msg);
                    });
                    messageBuffer = [];
                }
            };

            // Check periodically for overlay availability
            var checkInterval = setInterval(function() {
                if (window.overlay && window.overlay.log) {
                    window.flushConsoleBuffer();
                    clearInterval(checkInterval);
                }
            }, 50);

            // Clear interval after 5 seconds to avoid infinite polling
            setTimeout(function() {
                clearInterval(checkInterval);
            }, 5000);
        })();

        // Test console override
        console.log('TEST: Console override applied and buffering');

        // Debug timing helper
        function getTimestamp() {
            return new Date().toISOString();
        }

        function debugTime(label) {
            const now = Date.now();
            const elapsed = startTime ? ` (+${now - startTime}ms)` : '';
            console.log(`🔍 DEBUG [${getTimestamp()}] ${label}${elapsed}`);
        }

        // WebChannel fixture data functions
        async function fetchFixturesData(retryCount = 0) {
            const maxRetries = 10;
            const baseDelay = 1000; // 1 second

            try {
                debugTime('Fetching fixtures data via WebChannel');

                // Check if WebChannel is available
                if (!window.overlay || typeof window.overlay.getFixtureData !== 'function') {
                    console.log('DEBUG: WebChannel not ready, retrying...');
                    if (retryCount < maxRetries) {
                        const delay = baseDelay * Math.pow(2, retryCount);
                        console.log(`DEBUG: Retrying in ${delay}ms (attempt ${retryCount + 1}/${maxRetries + 1})`);
                        setTimeout(() => {
                            fetchFixturesData(retryCount + 1);
                        }, delay);
                    } else {
                        console.log('DEBUG: Max retries reached, using fallback data');
                        debugTime('Max retries reached for WebChannel connection');
                        showFallbackFixtures();
                    }
                    return;
                }

                console.log('DEBUG: WebChannel available, calling getFixtureData()');

                // Call WebChannel method to get fixture data
                const fixtureDataJson = await window.overlay.getFixtureData();
                console.log('DEBUG: WebChannel response received');
                console.log('DEBUG: Raw response =', fixtureDataJson);

                let data;
                try {
                    data = JSON.parse(fixtureDataJson);
                    console.log('DEBUG: WebChannel response JSON parsed successfully');
                    console.log('DEBUG: WebChannel response data =', data);
                } catch (parseError) {
                    console.log('DEBUG: Failed to parse WebChannel response as JSON');
                    throw new Error(`JSON parse error: ${parseError.message}`);
                }

                debugTime('Fixtures data received via WebChannel');

                if (data && Array.isArray(data) && data.length > 0) {
                    console.log('DEBUG: WebChannel returned fixtures data');
                    fixturesData = data;
                    renderFixtures();
                } else {
                    console.log('DEBUG: WebChannel response did not contain fixtures data');
                    debugTime('No fixtures data in WebChannel response');
                    showNoMatches('No fixtures available');
                }
            } catch (error) {
                console.log('DEBUG: Exception caught in fetchFixturesData');
                console.log('DEBUG: Error message =', error.message);
                console.log('DEBUG: Error stack =', error.stack);
                debugTime(`Failed to fetch fixtures data: ${error.message}`);

                // Check if we should retry
                if (retryCount < maxRetries) {
                    // Calculate delay with exponential backoff
                    const delay = baseDelay * Math.pow(2, retryCount);
                    console.log(`DEBUG: Retrying in ${delay}ms (attempt ${retryCount + 2}/${maxRetries + 1})`);

                    setTimeout(() => {
                        fetchFixturesData(retryCount + 1);
                    }, delay);
                } else {
                    console.log('DEBUG: Max retries reached, using fallback data');
                    debugTime('Max retries reached for fixtures data fetch');
                    // Show fallback data instead of error message
                    showFallbackFixtures();
                }
            }
        }


        // WebChannel configuration - no HTTP requests needed
        let webChannelReady = false;

        // Debug logging function that sends messages to Qt application logs
        function debugLog(message, level = 'info') {
            try {
                // Try to send to Qt WebChannel if available
                if (typeof qt !== 'undefined' && qt.webChannelTransport) {
                    // Send debug message to Qt application
                    if (window.sendDebugMessage) {
                        window.sendDebugMessage(`[FIXTURES] ${message}`);
                    }
                }
            } catch (e) {
                // Fallback to console if WebChannel not available - use original console to avoid recursion
                originalConsoleLog(`[FIXTURES FALLBACK] ${message}`);
            }

            // Always log to console as well for browser debugging - use original to avoid recursion
            originalConsoleLog(`🔍 DEBUG: ${message}`);
        }

        // Store original console.log before overriding
        const originalConsoleLog = console.log;

        // Debug console functionality
        let debugConsoleEnabled = false;
        const maxConsoleMessages = 50;
        let consoleMessageCount = 0;

        function addToDebugConsole(level, message) {
            if (!debugConsoleEnabled) return;

            const consoleOutput = document.getElementById('consoleOutput');
            if (!consoleOutput) return;

            const messageDiv = document.createElement('div');
            messageDiv.className = `console-message console-level-${level}`;

            const timestamp = new Date().toLocaleTimeString();
            messageDiv.innerHTML = `<span class="console-timestamp">[${timestamp}]</span> ${message}`;

            consoleOutput.appendChild(messageDiv);
            consoleMessageCount++;

            // Remove old messages if too many
            if (consoleMessageCount > maxConsoleMessages) {
                const firstMessage = consoleOutput.firstElementChild;
                if (firstMessage) {
                    consoleOutput.removeChild(firstMessage);
                    consoleMessageCount--;
                }
            }

            // Auto-scroll to bottom
            consoleOutput.scrollTop = consoleOutput.scrollHeight;
        }

        // Check if debug console should be enabled (via WebChannel or timeout)
        function checkDebugConsole() {
            const debugConsole = document.getElementById('debugConsole');
            if (debugConsole && debugConsole.classList.contains('show')) {
                debugConsoleEnabled = true;
                console.log('🔍 Debug console detected as enabled');
            }
        }

        // Check periodically for debug console enablement
        setInterval(checkDebugConsole, 500);

        // Setup WebChannel communication
        function setupWebChannel() {
            // Check if WebChannel is already set up by overlay.js
            if (window.overlay) {
                console.log('🔍 DEBUG: WebChannel already set up by overlay.js');

                // Test WebChannel
                if (window.overlay && window.overlay.log) {
                    window.overlay.log('TEST: WebChannel connection successful');
                }

                // Listen for data updates from Python
                if (window.overlay.dataUpdated) {
                    window.overlay.dataUpdated.connect(function(data) {
                        console.log('🔍 DEBUG: Received data update from Python:', data);
                        if (data && data.webServerBaseUrl) {
                            webServerBaseUrl = data.webServerBaseUrl;
                            webServerUrlReceived = true;
                            console.log('🔍 DEBUG: Web server base URL updated to:', webServerBaseUrl);

                            // If we were waiting for the URL, start fetching data now
                            if (document.readyState === 'complete' || document.readyState === 'interactive') {
                                console.log('🔍 DEBUG: Document ready, starting data fetch after URL update');
                                fetchFixturesData(0);
                            }
                        }
                        if (data && data.debugMode) {
                            console.log('🔍 DEBUG: Debug mode enabled, showing debug console');
                            const debugConsole = document.getElementById('debugConsole');
                            if (debugConsole) {
                                debugConsole.classList.add('show');
                                debugConsoleEnabled = true;
                            }
                        }
                    });
                }
                return;
            }

            // Fallback: setup WebChannel if overlay.js didn't do it
            if (typeof qt !== 'undefined' && qt.webChannelTransport) {
                try {
                    new QWebChannel(qt.webChannelTransport, function(channel) {
                        console.log('🔍 DEBUG: WebChannel connected successfully (fallback)');

                        // Connect to overlay object
                        window.overlay = channel.objects.overlay;

                        // Listen for data updates from Python
                        if (window.overlay && window.overlay.dataUpdated) {
                            window.overlay.dataUpdated.connect(function(data) {
                                console.log('🔍 DEBUG: Received data update from Python:', data);
                                // WebChannel is ready for fixture data
                                webChannelReady = true;
                                console.log('🔍 DEBUG: WebChannel ready for fixture data');
                                if (data && data.debugMode) {
                                    console.log('🔍 DEBUG: Debug mode enabled, showing debug console');
                                    const debugConsole = document.getElementById('debugConsole');
                                    if (debugConsole) {
                                        debugConsole.classList.add('show');
                                        debugConsoleEnabled = true;
                                    }
                                }
                            });
                        } else {
                            console.log('🔍 DEBUG: Overlay object not available in WebChannel');
                        }
                    });
                } catch (e) {
                    console.log('🔍 DEBUG: Failed to setup WebChannel:', e);
                }
            } else {
                console.log('🔍 DEBUG: WebChannel not available, using default webServerBaseUrl');
            }
        }

        // Console override is now applied at the beginning of the script with buffering

        
        
        // Show fallback sample matches when API is not available
        function showFallbackMatches() {
            console.log('🔍 DEBUG: Showing fallback sample matches - API FAILED');
            console.log('🔍 DEBUG: This indicates the API endpoints are not working properly');
            fixturesData = [
                {
                    id: 1,
                    match_number: 1,
                    fighter1_township: 'John Doe',
                    fighter2_township: 'Mike Smith',
                    venue_kampala_township: 'Sports Arena',
                    outcomes: [
                        { outcome_name: 'WIN1', outcome_value: 1.85 },
                        { outcome_name: 'X', outcome_value: 3.20 },
                        { outcome_name: 'WIN2', outcome_value: 2.10 },
                        { outcome_name: 'UNDER', outcome_value: 1.75 },
                        { outcome_name: 'OVER', outcome_value: 2.05 }
                    ]
                },
                {
                    id: 2,
                    match_number: 2,
                    fighter1_township: 'Alex Johnson',
                    fighter2_township: 'Chris Brown',
                    venue_kampala_township: 'Championship Hall',
                    outcomes: [
                        { outcome_name: 'WIN1', outcome_value: 2.20 },
                        { outcome_name: 'X', outcome_value: 3.10 },
                        { outcome_name: 'WIN2', outcome_value: 1.65 },
                        { outcome_name: 'UNDER', outcome_value: 1.90 },
                        { outcome_name: 'OVER', outcome_value: 1.95 }
                    ]
                }
            ];
            console.log('🔍 DEBUG: Fallback data loaded, rendering fixtures');
            renderFixtures();
        }

        // Show fallback fixtures data when API is not available yet (loading state)
        function showFallbackFixtures() {
            console.log('🔍 DEBUG: Showing fallback fixtures data - API not available yet');
            fixturesData = [
                {
                    id: 1,
                    match_number: 1,
                    fighter1_township: 'Loading...',
                    fighter2_township: 'Loading...',
                    venue_kampala_township: 'Loading...',
                    outcomes: [
                        { outcome_name: 'WIN1', outcome_value: '-' },
                        { outcome_name: 'X', outcome_value: '-' },
                        { outcome_name: 'WIN2', outcome_value: '-' },
                        { outcome_name: 'UNDER', outcome_value: '-' },
                        { outcome_name: 'OVER', outcome_value: '-' }
                    ]
                },
                {
                    id: 2,
                    match_number: 2,
                    fighter1_township: 'Loading...',
                    fighter2_township: 'Loading...',
                    venue_kampala_township: 'Loading...',
                    outcomes: [
                        { outcome_name: 'WIN1', outcome_value: '-' },
                        { outcome_name: 'X', outcome_value: '-' },
                        { outcome_name: 'WIN2', outcome_value: '-' },
                        { outcome_name: 'UNDER', outcome_value: '-' },
                        { outcome_name: 'OVER', outcome_value: '-' }
                    ]
                },
                {
                    id: 3,
                    match_number: 3,
                    fighter1_township: 'Loading...',
                    fighter2_township: 'Loading...',
                    venue_kampala_township: 'Loading...',
                    outcomes: [
                        { outcome_name: 'WIN1', outcome_value: '-' },
                        { outcome_name: 'X', outcome_value: '-' },
                        { outcome_name: 'WIN2', outcome_value: '-' },
                        { outcome_name: 'UNDER', outcome_value: '-' },
                        { outcome_name: 'OVER', outcome_value: '-' }
                    ]
                }
            ];
            console.log('🔍 DEBUG: Fallback fixtures data loaded, rendering fixtures');
            renderFixtures();
        }
        
        // Show fallback only when absolutely necessary
        function showFallbackWithDefaults(message) {
            console.log('API failed, showing no matches message instead of fallback');
            showNoMatches('No live matches available - API connection failed');
        }
        
        
        // Get default outcomes when API data is not available
        function getDefaultOutcomes() {
            return [
                { outcome_name: 'WIN1', outcome_value: 1.85 },
                { outcome_name: 'X', outcome_value: 3.20 },
                { outcome_name: 'WIN2', outcome_value: 2.10 },
                { outcome_name: 'UNDER', outcome_value: 1.75 },
                { outcome_name: 'OVER', outcome_value: 2.05 }
            ];
        }
        
        // Get timer state and start countdown
        async function getTimerStateAndStartCountdown() {
            console.log('🔍 DEBUG: getTimerStateAndStartCountdown called');

            try {
                // Get timer state from WebChannel
                const timerStateJson = await window.overlay.getTimerState();
                console.log('🔍 DEBUG: Raw timer state JSON:', timerStateJson);
                const timerState = JSON.parse(timerStateJson);

                console.log('🔍 DEBUG: Parsed timer state:', timerState);

                // Clear any existing countdown
                if (countdownInterval) {
                    clearInterval(countdownInterval);
                    countdownInterval = null;
                }

                if (timerState.running && timerState.remaining_seconds > 0) {
                    // Timer is running, show countdown
                    nextMatchStartTime = new Date(Date.now() + (timerState.remaining_seconds * 1000));

                    // Show next match info (generic message since we don't know which match)
                    const nextMatchInfo = document.getElementById('nextMatchInfo');
                    nextMatchInfo.textContent = `Next match starting in:`;
                    nextMatchInfo.style.display = 'block';
                    console.log('🔍 DEBUG: Timer countdown displayed');

                    // Start countdown
                    updateCountdown();
                    countdownInterval = setInterval(updateCountdown, 1000);
                    console.log('🔍 DEBUG: Countdown started with timer state');
                } else {
                    // No active timer, hide countdown
                    document.getElementById('nextMatchInfo').style.display = 'none';
                    document.getElementById('countdownTimer').style.display = 'none';
                    console.log('🔍 DEBUG: No active timer, countdown hidden');
                }
            } catch (error) {
                console.log('🔍 DEBUG: Failed to get timer state:', error);
                // Fallback: hide countdown
                document.getElementById('nextMatchInfo').style.display = 'none';
                document.getElementById('countdownTimer').style.display = 'none';
            }
        }

        // Update countdown display
        function updateCountdown() {
            if (!nextMatchStartTime) {
                return;
            }

            const now = new Date();
            const timeDiff = nextMatchStartTime - now;

            if (timeDiff <= 0) {
                // Match has started
                document.getElementById('countdownTimer').textContent = 'LIVE';
                document.getElementById('countdownTimer').className = 'countdown-timer';
                return;
            }

            const hours = Math.floor(timeDiff / (1000 * 60 * 60));
            const minutes = Math.floor((timeDiff % (1000 * 60 * 60)) / (1000 * 60));
            const seconds = Math.floor((timeDiff % (1000 * 60)) / 1000);

            let timeString = '';
            if (hours > 0) {
                timeString = `${hours}:${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`;
            } else {
                timeString = `${minutes}:${seconds.toString().padStart(2, '0')}`;
            }

            const countdownTimer = document.getElementById('countdownTimer');
            countdownTimer.textContent = timeString;

            // Add warning/urgent classes based on time remaining
            if (timeDiff <= 60000) { // 1 minute
                countdownTimer.className = 'countdown-timer urgent';
            } else if (timeDiff <= 300000) { // 5 minutes
                countdownTimer.className = 'countdown-timer warning';
            } else {
                countdownTimer.className = 'countdown-timer';
            }

            countdownTimer.style.display = 'block';
        }

        // Render the fixtures table
        function renderFixtures() {
            debugTime('Starting renderFixtures function');

            const loadingMessage = document.getElementById('loadingMessage');
            const fixturesContent = document.getElementById('fixturesContent');
            const noMatches = document.getElementById('noMatches');
            const tableHeader = document.getElementById('tableHeader');
            const tableBody = document.getElementById('tableBody');

            loadingMessage.style.display = 'none';
            noMatches.style.display = 'none';
            debugTime('UI elements updated - loading message hidden');

            if (!fixturesData || fixturesData.length === 0) {
                debugTime('No fixtures data available');
                showNoMatches('No matches available for today');
                return;
            }

            debugTime(`Processing ${fixturesData.length} fixtures`);

            // Get all available outcomes from the matches
            const allOutcomes = new Set();
            fixturesData.forEach(match => {
                if (match.outcomes) {
                    if (Array.isArray(match.outcomes)) {
                        // Handle array format from API
                        match.outcomes.forEach(outcome => {
                            const outcomeName = outcome.outcome_name || outcome.column_name;
                            if (outcomeName) {
                                allOutcomes.add(outcomeName);
                                console.log(`Found outcome: ${outcomeName} for match ${match.id}`);
                            }
                        });
                    } else if (typeof match.outcomes === 'object') {
                        // Handle dict format from database
                        Object.keys(match.outcomes).forEach(outcomeName => {
                            allOutcomes.add(outcomeName);
                            console.log(`Found outcome: ${outcomeName} for match ${match.id}`);
                        });
                    }
                }
            });

            console.log(`Total unique outcomes found: ${allOutcomes.size}`, Array.from(allOutcomes));
            
            // Sort outcomes: common ones first, then alphabetically
            const sortedOutcomes = Array.from(allOutcomes).sort((a, b) => {
                // Priority order for common outcomes
                const priority = {
                    'WIN1': 1, 'X': 2, 'WIN2': 3, 'DRAW': 4,
                    'UNDER': 5, 'OVER': 6, 'KO1': 7, 'KO2': 8,
                    'PTS1': 9, 'PTS2': 10, 'DKO': 11, 'RET1': 12, 'RET2': 13
                };
                
                const aPriority = priority[a] || 100;
                const bPriority = priority[b] || 100;
                
                if (aPriority !== bPriority) {
                    return aPriority - bPriority;
                }
                
                return a.localeCompare(b);
            });
            
            console.log('Sorted outcomes:', sortedOutcomes);
            
            // Create table header
            tableHeader.innerHTML = `
                <th>Match</th>
                <th>Fighters</th>
                <th>Venue</th>
                ${sortedOutcomes.map(outcome => `<th>${outcome}</th>`).join('')}
            `;
            
            // Create table body
            tableBody.innerHTML = '';
            
            fixturesData.slice(0, 5).forEach(match => {
                const row = document.createElement('tr');
                
                // Create outcomes map for quick lookup
                const outcomeMap = {};
                if (match.outcomes) {
                    if (Array.isArray(match.outcomes)) {
                        // Handle array format from API
                        match.outcomes.forEach(outcome => {
                            const outcomeName = outcome.outcome_name || outcome.column_name;
                            const outcomeValue = outcome.outcome_value || outcome.float_value;
                            if (outcomeName) {
                                outcomeMap[outcomeName] = outcomeValue;
                            }
                        });
                    } else if (typeof match.outcomes === 'object') {
                        // Handle dict format from database
                        Object.entries(match.outcomes).forEach(([key, value]) => {
                            outcomeMap[key] = value;
                        });
                    }
                }
                
                console.log(`Match ${match.id || match.match_number}: Found ${Object.keys(outcomeMap).length} outcomes`);
                
                row.innerHTML = `
                    <td class="match-info">#${match.match_number || match.id || 'N/A'}</td>
                    <td class="fighter-names">
                        ${match.fighter1_township || match.fighter1 || 'Fighter 1'}<br>vs<br>${match.fighter2_township || match.fighter2 || 'Fighter 2'}
                    </td>
                    <td class="venue-info">${match.venue_kampala_township || match.venue || 'TBD'}</td>
                    ${sortedOutcomes.map(outcome => {
                        const odds = outcomeMap[outcome];
                        const isUnderOver = outcome === 'UNDER' || outcome === 'OVER';
                        const oddsClass = isUnderOver ? 'odds-value under-over' : 'odds-value';
                        const displayValue = odds !== undefined && odds !== null ? parseFloat(odds).toFixed(2) : '-';
                        return `<td><span class="${oddsClass}">${displayValue}</span></td>`;
                    }).join('')}
                `;
                
                tableBody.appendChild(row);
            });
            
            fixturesContent.style.display = 'block';
            debugTime('Fixtures table rendered and displayed');

            // Get timer state and start countdown
            getTimerStateAndStartCountdown();
            debugTime('Countdown initialization completed');
        }
        
        // Show no matches message
        function showNoMatches(message) {
            document.getElementById('loadingMessage').style.display = 'none';
            document.getElementById('fixturesContent').style.display = 'none';
            const noMatches = document.getElementById('noMatches');
            noMatches.textContent = message;
            noMatches.style.display = 'block';
        }
        
        // Initialize when DOM is loaded
        document.addEventListener('DOMContentLoaded', function() {
            startTime = Date.now();
            debugTime('DOM Content Loaded - Starting fixtures overlay initialization');

            // Setup WebChannel first
            setupWebChannel();

            // Show loading message initially
            document.getElementById('fixturesContent').style.display = 'none';
            document.getElementById('noMatches').style.display = 'none';
            document.getElementById('loadingMessage').style.display = 'block';
            document.getElementById('loadingMessage').textContent = 'Loading live fixture data...';

            debugTime('UI initialized - Loading message displayed');

            // Wait briefly for WebChannel to connect
            setTimeout(() => {
                console.log('🔍 DEBUG: Starting fixture data fetch via WebChannel');

                // Fetch fixtures data via WebChannel
                debugTime('Fetching fixtures data via WebChannel');
                fetchFixturesData();

                // Set up periodic refresh every 30 seconds
                setInterval(() => {
                    debugTime('Periodic refresh: fetching updated fixtures data');
                    fetchFixturesData(0); // Start with retry count 0 for periodic refreshes
                }, 30000);

                // Show no matches if no data after 5 seconds total
                setTimeout(() => {
                    if (!fixturesData || fixturesData.length === 0) {
                        debugTime('No data received after 5 seconds - showing waiting message');
                        showNoMatches('Waiting for fixture data...');
                    } else {
                        debugTime('Data was received before 5 second timeout');
                    }
                }, 5000);
            }, 50); // Wait 50ms for WebChannel setup
        });
        
    </script>

</body>
</html>