<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>Match 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: 'Match Overlay v1.0 loaded';
            position: absolute;
            top: 5px;
            left: 5px;
            color: rgba(255,255,255,0.5);
            font-size: 10px;
            z-index: 9999;
        }

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

        /* 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;
            width: 66%;
            max-width: 66%;
            max-height: 80%;
            overflow-y: auto;
            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;
        }

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


        .match-title {
            font-size: 48px;
            font-weight: bold;
            color: rgba(255, 255, 255, 0.9);
            text-align: center;
            margin-bottom: 20px;
            text-shadow: 2px 2px 4px rgba(0, 0, 0, 0.5);
        }

        .match-header {
            display: flex;
            justify-content: space-between;
            align-items: flex-start;
            margin-bottom: 30px;
            width: 100%;
        }

        .fighters-section {
            flex: 1;
            flex-basis: 50%;
            text-align: center;
            display: flex;
            align-items: center;
            justify-content: center;
        }

        .fighter-names {
            display: flex;
            flex-direction: column;
            align-items: center;
            gap: 15px;
        }

        .fighter1-name, .fighter2-name {
            font-size: 72px;
            font-weight: bold;
            color: white;
            text-shadow: 3px 3px 6px rgba(0, 0, 0, 0.7);
            line-height: 1.1;
        }

        .vs-text {
            font-size: 48px;
            font-weight: bold;
            color: #ffeb3b;
            text-shadow: 2px 2px 4px rgba(0, 0, 0, 0.8);
            background: rgba(0, 0, 0, 0.6);
            padding: 12px 24px;
            border-radius: 16px;
            border: 3px solid #ffeb3b;
            margin: 16px 0;
        }

        .venue-timer-section {
            flex: 1;
            flex-basis: 50%;
            text-align: center;
            display: flex;
            flex-direction: column;
            align-items: center;
            gap: 24px;
        }

        .venue-label {
            font-size: 36px;
            font-weight: bold;
            color: rgba(255, 255, 255, 0.8);
            text-shadow: 1px 1px 2px rgba(0, 0, 0, 0.5);
            margin-bottom: -6px;
        }

        .venue-display {
            font-size: 72px;
            font-weight: bold;
            color: rgba(255, 255, 255, 0.95);
            text-shadow: 2px 2px 4px rgba(0, 0, 0, 0.6);
            line-height: 1.1;
        }

        .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: 64px;
            font-weight: bold;
            margin-bottom: 24px;
            text-shadow: 2px 2px 4px rgba(0, 0, 0, 0.8);
            background: rgba(0, 0, 0, 0.3);
            padding: 12px 24px;
            border-radius: 16px;
            border: 3px 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); }
        }
        
        .outcomes-grid {
            display: grid;
            gap: 10px;
            width: 100%;
            max-width: 1200px;
            margin-top: 20px;
            justify-content: center;
        }

        .outcome-cell {
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            min-height: 80px;
            border: 2px solid rgba(255, 255, 255, 0.3);
            border-radius: 8px;
        }

        .outcome-name {
            font-size: 28px;
            font-weight: bold;
            color: rgba(255, 255, 255, 0.9);
            margin-bottom: 8px;
            text-shadow: 1px 1px 2px rgba(0, 0, 0, 0.5);
        }

        .outcome-value {
            font-size: 36px;
            font-weight: bold;
            color: #ffffff;
            text-shadow: 1px 1px 2px rgba(0, 0, 0, 0.5);
        }

        .under-over-cell {
            background: rgba(40, 167, 69, 0.2);
            border: 1px solid rgba(40, 167, 69, 0.3);
        }

        .under-over-cell .outcome-value {
            color: #28a745;
        }
        
        .fixtures-table tbody tr:hover td {
            background: rgba(255, 255, 255, 0.15);
        }
        
        .match-info {
            font-weight: bold;
            color: #ffffff;
        }
        
        .fighter-names {
            font-size: 14px;
            color: #e6f3ff;
        }
        
        .venue-info {
            font-size: 13px;
            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: 18px;
            padding: 40px;
        }
        
        .no-matches {
            text-align: center;
            color: rgba(255, 255, 255, 0.8);
            font-size: 16px;
            padding: 30px;
            font-style: italic;
        }
        
        .fixture-info {
            text-align: center;
            color: rgba(255, 255, 255, 0.9);
            font-size: 14px;
            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: 24px;
            }
            
            .fixtures-table {
                font-size: 14px;
            }
            
            .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: 20px;
                margin-bottom: 15px;
            }
            
            .fixtures-table {
                font-size: 12px;
            }
            
            .fixtures-table th,
            .fixtures-table td {
                padding: 6px 4px;
            }
            
            .odds-value {
                padding: 2px 4px;
                font-size: 11px;
            }
        }
        
        /* Scrollbar styling */
        .fixtures-panel::-webkit-scrollbar {
            width: 8px;
        }

        .fixtures-panel::-webkit-scrollbar-track {
            background: rgba(255, 255, 255, 0.1);
            border-radius: 4px;
        }

        .fixtures-panel::-webkit-scrollbar-thumb {
            background: rgba(255, 255, 255, 0.3);
            border-radius: 4px;
        }

        .fixtures-panel::-webkit-scrollbar-thumb:hover {
            background: rgba(255, 255, 255, 0.5);
        }

    </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">
            <!-- Title -->
            <div class="match-title">Next Match:</div>

            <!-- Top section with fighters and venue/timer -->
            <div class="match-header">
                <div class="fighters-section">
                    <div class="fighter-names" id="fighterNames">
                        <div class="fighter1-name">Fighter 1</div>
                        <div class="vs-text">VS</div>
                        <div class="fighter2-name">Fighter 2</div>
                    </div>
                </div>
                <div class="venue-timer-section">
                    <div class="venue-label">VENUE:</div>
                    <div class="venue-display" id="matchVenue">Venue</div>
                    <div class="next-match-info" id="nextMatchInfo" style="display: none;"></div>
                    <div class="countdown-timer" id="countdownTimer" style="display: none;"></div>
                </div>
            </div>

            <!-- Bottom section with odds grid -->
            <div class="loading-message" id="loadingMessage" style="display: none;">Loading match data...</div>
            <div id="matchContent" style="display: none;">
                <div class="outcomes-grid" id="outcomesGrid">
                    <!-- Grid items will be populated by JavaScript -->
                </div>
            </div>
            <div class="no-matches" id="noMatches" style="display: none;">
                No matches available for betting
            </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}`);
        }

        // Web server configuration - will be set via WebChannel
        let webServerBaseUrl = 'http://127.0.0.1:5001';  // Default fallback
        let webServerUrlReceived = 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(`[MATCH] ${message}`);
                    }
                }
            } catch (e) {
                // Fallback to console if WebChannel not available - use original console to avoid recursion
                originalConsoleLog(`[MATCH 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 for debug console enablement once after a delay
        setTimeout(checkDebugConsole, 1000);

        // 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');
                                fetchFixtureData();
                            }
                        }
                        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;
                            }
                        }
                        if (data && data.timer_update) {
                            console.log('🔍 DEBUG: Timer update received (fallback):', data.timer_update);
                            // Handle timer updates from match_timer
                            const timerData = data.timer_update;
                            if (timerData.running && timerData.remaining_seconds !== undefined) {
                                // Clear any existing countdown
                                if (countdownInterval) {
                                    clearInterval(countdownInterval);
                                    countdownInterval = null;
                                }

                                // Set next match start time
                                nextMatchStartTime = new Date(Date.now() + (timerData.remaining_seconds * 1000));

                                // Show next match info
                                const nextMatchInfo = document.getElementById('nextMatchInfo');
                                if (nextMatchInfo) {
                                    nextMatchInfo.textContent = `Next match starting in:`;
                                    nextMatchInfo.style.display = 'block';
                                }

                                // Start countdown
                                updateCountdown();
                                countdownInterval = setInterval(updateCountdown, 1000);
                                console.log('🔍 DEBUG: Countdown started from timer update');
                            } else {
                                // No active timer, hide countdown
                                const nextMatchInfo = document.getElementById('nextMatchInfo');
                                const countdownTimer = document.getElementById('countdownTimer');
                                if (nextMatchInfo) nextMatchInfo.style.display = 'none';
                                if (countdownTimer) countdownTimer.style.display = 'none';

                                // Clear countdown interval
                                if (countdownInterval) {
                                    clearInterval(countdownInterval);
                                    countdownInterval = null;
                                }
                            }
                        }
                        if (data && data.timer_update) {
                            console.log('🔍 DEBUG: Timer update received:', data.timer_update);
                            // Handle timer updates from match_timer
                            const timerData = data.timer_update;
                            if (timerData.running && timerData.remaining_seconds !== undefined) {
                                // Clear any existing countdown
                                if (countdownInterval) {
                                    clearInterval(countdownInterval);
                                    countdownInterval = null;
                                }

                                // Set next match start time
                                nextMatchStartTime = new Date(Date.now() + (timerData.remaining_seconds * 1000));

                                // Show next match info
                                const nextMatchInfo = document.getElementById('nextMatchInfo');
                                if (nextMatchInfo) {
                                    nextMatchInfo.textContent = `Next match starting in:`;
                                    nextMatchInfo.style.display = 'block';
                                }

                                // Start countdown
                                updateCountdown();
                                countdownInterval = setInterval(updateCountdown, 1000);
                                console.log('🔍 DEBUG: Countdown started from timer update');
                            } else {
                                // No active timer, hide countdown
                                const nextMatchInfo = document.getElementById('nextMatchInfo');
                                const countdownTimer = document.getElementById('countdownTimer');
                                if (nextMatchInfo) nextMatchInfo.style.display = 'none';
                                if (countdownTimer) countdownTimer.style.display = 'none';

                                // Clear countdown interval
                                if (countdownInterval) {
                                    clearInterval(countdownInterval);
                                    countdownInterval = null;
                                }
                            }
                        }
                    });
                }
                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);
                                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');
                                        fetchFixtureData();
                                    }
                                }
                                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
        
        // Fetch fixture data using WebChannel instead of API fetch
        async function fetchFixtureData() {
            try {
                debugTime('Fetching fixture data using WebChannel');
                console.log('DEBUG: [MATCH] Attempting to get fixture data from WebChannel');
                console.log('DEBUG: [MATCH] window.overlay exists:', !!window.overlay);
                console.log('DEBUG: [MATCH] window.overlay.getFixtureData exists:', !!(window.overlay && window.overlay.getFixtureData));

                if (window.overlay && window.overlay.getFixtureData) {
                    // Get fixture data from Qt WebChannel (returns a Promise)
                    const fixtureJson = await window.overlay.getFixtureData();
                    console.log('DEBUG: [MATCH] Received fixture data from WebChannel:', fixtureJson);

                    if (fixtureJson) {
                        try {
                            fixturesData = JSON.parse(fixtureJson);
                            console.log('DEBUG: [MATCH] Parsed fixture data:', fixturesData);
                            console.log('DEBUG: [MATCH] fixturesData.length:', fixturesData ? fixturesData.length : 'null');
                            debugTime('Fixture data received from WebChannel');

                            if (fixturesData && fixturesData.length > 0) {
                                console.log('DEBUG: [MATCH] WebChannel returned fixture data, calling renderMatch()');
                                renderMatch();
                            } else {
                                console.log('DEBUG: [MATCH] WebChannel returned empty fixture data');
                                debugTime('No fixture data in WebChannel response');
                                showNoMatches('No matches available');
                            }
                        } catch (parseError) {
                            console.log('DEBUG: [MATCH] Failed to parse fixture data from WebChannel:', parseError);
                            debugTime(`Failed to parse fixture data: ${parseError.message}`);
                            showNoMatches('Unable to load matches - data parsing failed');
                        }
                    } else {
                        console.log('DEBUG: [MATCH] WebChannel returned null/empty fixture data');
                        debugTime('No fixture data from WebChannel');
                        showNoMatches('No matches available');
                    }
                } else {
                    console.log('DEBUG: [MATCH] WebChannel overlay.getFixtureData not available');
                    console.log('DEBUG: [MATCH] window object keys:', Object.keys(window));
                    if (window.overlay) {
                        console.log('DEBUG: [MATCH] window.overlay keys:', Object.keys(window.overlay));
                    }
                    debugTime('WebChannel not available for fixture data');
                    showNoMatches('Unable to load matches - WebChannel not available');
                }
            } catch (error) {
                console.log('DEBUG: [MATCH] Exception caught in fetchFixtureData');
                console.log('DEBUG: [MATCH] Error message =', error.message);
                console.log('DEBUG: [MATCH] Error stack =', error.stack);
                debugTime(`Failed to fetch fixture data: ${error.message}`);
                showNoMatches('Unable to load matches - WebChannel error');
            }
        }
        
        // Show fallback sample matches when API is not available
        function showFallbackMatches() {
            console.log('Showing fallback sample matches');
            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 }
                    ]
                }
            ];
            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');
        }
        
        // Enhance matches with outcomes data by fetching match details for each
        async function enhanceMatchesWithOutcomes() {
            try {
                console.log('Enhancing matches with outcomes data...');
                
                // For each match, try to get its outcomes
                for (let i = 0; i < fixturesData.length; i++) {
                    const match = fixturesData[i];
                    
                    try {
                        // Try to get match outcomes from fixture details API
                        const response = await fetch(`${webServerBaseUrl}/api/fixtures/${match.fixture_id}`);
                        const fixtureData = await response.json();
                        
                        if (fixtureData.success && fixtureData.matches) {
                            // Find this specific match in the fixture data
                            const matchWithOutcomes = fixtureData.matches.find(m => m.id === match.id);
                            
                            if (matchWithOutcomes && matchWithOutcomes.outcomes) {
                                console.log(`Found ${matchWithOutcomes.outcomes.length} outcomes for match ${match.id}`);
                                fixturesData[i].outcomes = matchWithOutcomes.outcomes;
                            } else {
                                console.log(`No outcomes found for match ${match.id}, using defaults`);
                                fixturesData[i].outcomes = getDefaultOutcomes();
                            }
                        } else {
                            console.log(`Failed to get fixture details for match ${match.id}`);
                            fixturesData[i].outcomes = getDefaultOutcomes();
                        }
                    } catch (error) {
                        console.error(`Error fetching outcomes for match ${match.id}:`, error);
                        fixturesData[i].outcomes = getDefaultOutcomes();
                    }
                }
                
                console.log('Finished enhancing matches with outcomes');
            } catch (error) {
                console.error('Error enhancing matches with outcomes:', error);
            }
        }
        
        // 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 (same as fixtures.html)
        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 focused match view (first match in bet status) - TV titling style
        function renderMatch() {
            debugTime('Starting renderMatch function');

            const loadingMessage = document.getElementById('loadingMessage');
            const matchContent = document.getElementById('matchContent');
            const noMatches = document.getElementById('noMatches');
            const matchVenue = document.getElementById('matchVenue');

            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`);
            console.log('DEBUG: fixturesData =', fixturesData);

            // Find the first match (next upcoming match)
            const nextMatch = fixturesData[0]; // Get first match from the 5 retrieved

            if (!nextMatch) {
                showNoMatches('No matches available');
                return;
            }

            console.log('Rendering next match for TV titling:', nextMatch);
            console.log('DEBUG: nextMatch properties:', Object.keys(nextMatch));
            console.log('DEBUG: nextMatch.fighter1_township =', nextMatch.fighter1_township);
            console.log('DEBUG: nextMatch.fighter2_township =', nextMatch.fighter2_township);
            console.log('DEBUG: nextMatch.venue_kampala_township =', nextMatch.venue_kampala_township);

            // Update match title with match number
            const matchTitle = document.querySelector('.match-title');
            const matchNumber = nextMatch.match_number || nextMatch.id || 'N/A';
            if (matchTitle) matchTitle.textContent = `Next Match: #${matchNumber}`;

            // Update fighter names in top left (multi-line layout)
            const fighter1 = nextMatch.fighter1_township || nextMatch.fighter1 || 'Fighter 1';
            const fighter2 = nextMatch.fighter2_township || nextMatch.fighter2 || 'Fighter 2';

            const fighter1Name = document.querySelector('.fighter1-name');
            const fighter2Name = document.querySelector('.fighter2-name');

            if (fighter1Name) fighter1Name.textContent = fighter1;
            if (fighter2Name) fighter2Name.textContent = fighter2;

            // Update venue in top right
            const venue = nextMatch.venue_kampala_township || nextMatch.venue || 'TBD';
            matchVenue.textContent = venue;

            // Get outcomes for this match (comes as object/dict from database)
            let outcomes = nextMatch.outcomes || {};
            console.log('DEBUG: Raw outcomes object:', outcomes);
            console.log('DEBUG: Outcomes type:', typeof outcomes);
            console.log('DEBUG: Outcomes keys:', Object.keys(outcomes));

            // Convert outcomes object to array format for processing
            let outcomesArray = [];
            if (typeof outcomes === 'object' && outcomes !== null) {
                // Handle dict format from database
                Object.entries(outcomes).forEach(([key, value]) => {
                    outcomesArray.push({
                        outcome_name: key,
                        outcome_value: value
                    });
                });
            }

            if (outcomesArray.length === 0) {
                console.log('No outcomes found for match, using defaults');
                // Use default outcomes if none available
                outcomesArray = getDefaultOutcomes();
            }

            console.log(`Found ${outcomesArray.length} outcomes for match ${nextMatch.id || nextMatch.match_number}`);

            // Sort outcomes: common ones first, then alphabetically
            const sortedOutcomes = outcomesArray.sort((a, b) => {
                const aName = a.outcome_name || '';
                const bName = b.outcome_name || '';

                // 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[aName] || 100;
                const bPriority = priority[bName] || 100;

                if (aPriority !== bPriority) {
                    return aPriority - bPriority;
                }

                return aName.localeCompare(bName);
            });

            // Create a balanced grid where each cell contains both outcome name and value
            // Use square grid sizing (round up to next square)
            const totalOutcomes = sortedOutcomes.length;
            const gridSize = Math.ceil(Math.sqrt(totalOutcomes));

            // Set CSS grid columns
            const outcomesGrid = document.getElementById('outcomesGrid');
            outcomesGrid.style.gridTemplateColumns = `repeat(${gridSize}, 1fr)`;

            let gridHTML = '';

            // Create grid items for each outcome
            sortedOutcomes.forEach(outcome => {
                const outcomeValue = outcome.outcome_value;
                const displayValue = outcomeValue !== undefined && outcomeValue !== null ? parseFloat(outcomeValue).toFixed(2) : '-';
                const isUnderOver = outcome.outcome_name === 'UNDER' || outcome.outcome_name === 'OVER';
                const cellClass = isUnderOver ? 'outcome-cell under-over-cell' : 'outcome-cell';
                gridHTML += `<div class="${cellClass}">
                    <div class="outcome-name">${outcome.outcome_name}</div>
                    <div class="outcome-value">${displayValue}</div>
                </div>`;
            });

            outcomesGrid.innerHTML = gridHTML;

            matchContent.style.display = 'block';
            debugTime('Match 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('matchContent').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 match overlay initialization');

            // Setup WebChannel first
            setupWebChannel();

            // Show loading message initially
            document.getElementById('matchContent').style.display = 'none';
            document.getElementById('noMatches').style.display = 'none';
            document.getElementById('loadingMessage').style.display = 'block';
            document.getElementById('loadingMessage').textContent = 'Loading next match data...';

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

            // Wait briefly for WebChannel to connect and potentially receive webServerBaseUrl
            setTimeout(() => {
                if (!webServerUrlReceived) {
                    console.log('🔍 DEBUG: WebServerBaseUrl not received via WebChannel, proceeding with WebChannel data fetch');
                }

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

                // Check for timer state immediately when page loads
                debugTime('Checking timer state on page load');
                getTimerStateAndStartCountdown();

                // Fetch fixture data directly from WebChannel
                debugTime('Fetching fixture data from WebChannel');
                fetchFixtureData();

                // Set up periodic refresh every 30 seconds
                setTimeout(function refreshData() {
                    debugTime('Periodic refresh: fetching updated fixture data');
                    fetchFixtureData();
                    setTimeout(refreshData, 30000);
                }, 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 match data...');
                    } else {
                        debugTime('Data was received before 5 second timeout');
                    }
                }, 5000);
            }, 50); // Wait 50ms for WebChannel setup
        });
    </script>

    <!--
    IMPORTANT: When creating or editing custom templates, always maintain these two script tags:
    1. qrc:///qtwebchannel/qwebchannel.js - Required for Qt WebChannel communication
    2. overlay://overlay.js - Required for overlay functionality and data updates
    
    These scripts enable communication between the Qt application and the overlay template.
    Without them, the template will not receive data updates or function properly.
    
    NOTE: When editing this template or creating new ones, never remove these script sources!
    The overlay:// custom scheme ensures JavaScript files work for both built-in and uploaded templates.
    -->
    <script src="qrc:///qtwebchannel/qwebchannel.js"></script>
    <script src="overlay://overlay.js"></script>
</body>
</html>