<!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;
        }

        /* License Top Bar */
        .license-bar {
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            background: rgba(0, 123, 255, 0.85);
            border-radius: 0 0 20px 20px;
            padding: 15px 30px;
            text-align: center;
            z-index: 1000;
            backdrop-filter: blur(10px);
            border: 2px solid rgba(255, 255, 255, 0.1);
            border-top: none;
        }

        .license-text {
            color: rgba(255, 255, 255, 0.95);
            font-size: 16px;
            font-weight: bold;
            text-shadow: 2px 2px 4px rgba(0, 0, 0, 0.6);
            line-height: 1.4;
            word-wrap: break-word;
        }
        
        .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 */
        }

        .results-bottom-bar {
            position: absolute;
            bottom: 20px;
            left: 20px;
            right: 20px;
            background: rgba(0, 123, 255, 0.85);
            border-radius: 15px;
            padding: 15px 20px;
            box-shadow: 0 4px 16px rgba(0, 0, 0, 0.3);
            backdrop-filter: blur(10px);
            border: 2px solid rgba(255, 255, 255, 0.1);
            color: white;
            font-size: 24px;
            text-align: center;
            z-index: 1001;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
        }

        
        .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>

<!-- License Top Bar -->
<div class="license-bar" id="licenseBar">
    <div class="license-text" id="licenseText">Loading license text...</div>
</div>

<div class="overlay-container">
        <div class="fixtures-panel" id="fixturesPanel">
            <div class="fixtures-title" id="fixturesTitle">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>

        <!-- Results Bottom Bar -->
        <div class="results-bottom-bar" id="resultsBottomBar" style="display: none;">
            <div id="resultsContent">
                <!-- Match results will be populated by JavaScript -->
            </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;
        let licenseText = 'Loading license text...';

        // 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 }
            ];
        }

        // Fetch license text from WebChannel
        async function fetchLicenseText() {
            try {
                // Try to get license text from Qt WebChannel
                if (window.overlay && window.overlay.getLicenseText) {
                    const licenseTextData = await window.overlay.getLicenseText();
                    if (licenseTextData) {
                        // Parse the JSON response to extract license_text
                        try {
                            const licenseData = JSON.parse(licenseTextData);
                            if (licenseData.license_text) {
                                licenseText = licenseData.license_text;
                                updateLicenseDisplay();
                                console.log('License text loaded from WebChannel:', licenseText);
                            } else {
                                console.log('No license_text found in WebChannel response');
                            }
                        } catch (parseError) {
                            console.log('Failed to parse license text JSON from WebChannel:', parseError);
                            // Keep default text if parsing fails
                        }
                    }
                }
            } catch (error) {
                console.log('Could not fetch license text from WebChannel, using default');
                // Keep default text if WebChannel is not available
            }
        }

        // Update license text display
        function updateLicenseDisplay() {
            const licenseBar = document.getElementById('licenseBar');
            const licenseElement = document.getElementById('licenseText');

            if (licenseElement && licenseBar) {
                if (licenseText && licenseText.trim() !== '') {
                    licenseElement.textContent = licenseText;
                    licenseBar.style.display = 'block';
                } else {
                    licenseBar.style.display = 'none';
                }
            }
        }
        
        // 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';
        }

        // Update fixtures title based on content
        function updateFixturesTitle(fixturesData) {
            const fixturesTitle = document.getElementById('fixturesTitle');
            if (!fixturesTitle) return;

            // Check if we have yesterday's matches (incomplete from previous day)
            const now = new Date();
            const today = new Date(now.getFullYear(), now.getMonth(), now.getDate());
            const yesterday = new Date(today);
            yesterday.setDate(yesterday.getDate() - 1);

            let hasYesterdayMatches = false;
            let hasTodayMatches = false;

            fixturesData.forEach(match => {
                if (match.start_time) {
                    const matchDate = new Date(match.start_time);
                    const matchDay = new Date(matchDate.getFullYear(), matchDate.getMonth(), matchDate.getDate());

                    if (matchDay.getTime() === yesterday.getTime()) {
                        hasYesterdayMatches = true;
                    } else if (matchDay.getTime() === today.getTime()) {
                        hasTodayMatches = true;
                    }
                }
            });

            if (hasYesterdayMatches && hasTodayMatches) {
                fixturesTitle.textContent = 'Today & Yesterday matches:';
            } else if (hasYesterdayMatches) {
                fixturesTitle.textContent = 'Yesterday matches:';
            } else {
                fixturesTitle.textContent = 'Today matches:';
            }

            console.log(`Updated fixtures title: ${fixturesTitle.textContent} (yesterday: ${hasYesterdayMatches}, today: ${hasTodayMatches})`);
        }

        // 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');
            const fixturesTitle = document.getElementById('fixturesTitle');

            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');
                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');

            // Fetch and display last match results
            fetchLastMatchResults();
        }
        
        // 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';
        }

        // Fetch and display last 3 match results
        async function fetchLastMatchResults() {
            try {
                debugTime('Fetching last match results');

                // Try WebChannel first (same as license text)
                if (window.overlay && typeof window.overlay.getCompletedMatches === 'function') {
                    const completedMatchesJson = await window.overlay.getCompletedMatches();
                    const completedMatches = JSON.parse(completedMatchesJson);
                    if (completedMatches && completedMatches.length > 0) {
                        // Take last 3 matches (already ordered by end_time desc in WebChannel)
                        const lastMatches = completedMatches.slice(0, 3);
                        renderMatchResults(lastMatches);
                        return;
                    }
                }

                // Fallback: try to fetch from web API if webServerBaseUrl is available
                if (webServerBaseUrl) {
                    const response = await fetch(`${webServerBaseUrl}/api/fixtures`);
                    if (response.ok) {
                        const fixturesData = await response.json();
                        if (fixturesData.success && fixturesData.fixtures) {
                            // Flatten all matches from all fixtures and filter completed ones
                            const allMatches = [];
                            fixturesData.fixtures.forEach(fixture => {
                                if (fixture.matches) {
                                    fixture.matches.forEach(match => {
                                        if (match.status === 'done' && match.result) {
                                            allMatches.push(match);
                                        }
                                    });
                                }
                            });

                            // Sort by end_time or created_at descending (most recent first)
                            allMatches.sort((a, b) => {
                                const aTime = new Date(a.end_time || a.updated_at || a.created_at);
                                const bTime = new Date(b.end_time || b.updated_at || b.created_at);
                                return bTime - aTime;
                            });

                            // Take last 3 matches
                            const lastMatches = allMatches.slice(0, 3);
                            if (lastMatches.length > 0) {
                                renderMatchResults(lastMatches);
                                return;
                            }
                        }
                    }
                }

                // No results available
                debugTime('No match results available');
                document.getElementById('resultsBottomBar').style.display = 'none';

            } catch (error) {
                console.log('DEBUG: Failed to fetch match results:', error);
                document.getElementById('resultsBottomBar').style.display = 'none';
            }
        }

        // Render match results in the bottom bar
        function renderMatchResults(matches) {
            const resultsContent = document.getElementById('resultsContent');
            if (!resultsContent) return;

            let resultsText = 'RESULTS: ';

            matches.forEach((match, index) => {
                const matchNumber = match.match_number || match.id || 'N/A';
                const fighter1 = match.fighter1_township || match.fighter1 || 'Fighter 1';
                const fighter2 = match.fighter2_township || match.fighter2 || 'Fighter 2';
                const result = match.result || 'Unknown';
                const underOver = match.under_over_result || '';

                const resultText = underOver ? `${result} (${underOver})` : result;

                resultsText += `Match #${matchNumber}: ${fighter1} vs ${fighter2} = ${resultText}`;
                if (index < matches.length - 1) {
                    resultsText += ' | ';
                }
            });

            resultsContent.textContent = resultsText;
            document.getElementById('resultsBottomBar').style.display = 'block';

            debugTime(`Rendered ${matches.length} match results`);
        }
        
        // 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 for WebChannel to be ready before fetching data
            waitForWebChannelReady(() => {
                console.log('🔍 DEBUG: WebChannel ready, starting data fetch');

                // Fetch license text now that WebChannel is ready
                fetchLicenseText();

                // 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);
            });
        });

        // Wait for WebChannel to be ready
        function waitForWebChannelReady(callback, maxWait = 10000) {
            const startTime = Date.now();

            const checkReady = () => {
                if (window.overlay && window.overlay.getLicenseText) {
                    console.log('🔍 DEBUG: WebChannel ready for license text fetch');
                    callback();
                } else if (Date.now() - startTime > maxWait) {
                    console.warn('🔍 DEBUG: WebChannel not ready after max wait time, proceeding anyway');
                    callback();
                } else {
                    setTimeout(checkReady, 100);
                }
            };

            checkReady();
        }
        
    </script>

</body>
</html>