<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>Results 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;
            overflow: hidden;
            width: 100vw;
            height: 100vh;
            position: relative;
        }
        
        /* Debug indicator to verify CSS is loaded */
        body::before {
            content: 'Results Overlay v1.0 loaded';
            position: absolute;
            top: 5px;
            left: 5px;
            color: rgba(255,255,255,0.5);
            font-size: 10px;
            z-index: 9999;
        }
        
        .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;
        }

        .results-panel {
            background: rgba(0, 123, 255, 0.85);
            border-radius: 20px;
            padding: 30px;
            max-width: 90%;
            max-height: 85%;
            overflow: visible;
            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; /* Initially transparent */
            padding-bottom: 50px;
            display: flex;
            transition: opacity 0.5s ease-out;
        }

        .results-panel.visible {
            opacity: 1;
        }

        .results-content {
            width: 100%;
            opacity: 0;
            transform: translateY(20px);
            transition: all 0.5s ease-out;
        }

        .results-content.visible {
            opacity: 1;
            transform: translateY(0);
        }
        
        .results-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);
        }

        .fighters-display {
            text-align: center;
            margin-bottom: 30px;
        }

        .fighter-names {
            font-size: 48px;
            font-weight: bold;
            color: #ffffff;
            text-shadow: 3px 3px 6px rgba(0, 0, 0, 0.6);
            letter-spacing: 2px;
            text-align: center;
            line-height: 1.2;
        }

        .main-result-display {
            text-align: center;
            margin-bottom: 20px;
        }

        .main-result-text {
            font-size: 72px;
            font-weight: bold;
            color: #ffffff;
            text-shadow: 4px 4px 8px rgba(0, 0, 0, 0.6);
            letter-spacing: 4px;
            text-align: center;
            background: rgba(255, 255, 255, 0.1);
            border-radius: 15px;
            padding: 20px 40px;
            border: 3px solid rgba(255, 255, 255, 0.3);
            display: inline-block;
            min-width: 300px;
        }

        .under-over-display {
            text-align: center;
            margin-bottom: 40px;
        }

        .under-over-text {
            font-size: 48px;
            font-weight: bold;
            color: #e6f3ff;
            text-shadow: 3px 3px 6px rgba(0, 0, 0, 0.6);
            letter-spacing: 2px;
            text-align: center;
            background: rgba(40, 167, 69, 0.3);
            border-radius: 10px;
            padding: 15px 30px;
            border: 2px solid rgba(40, 167, 69, 0.5);
            display: inline-block;
            min-width: 200px;
        }

        .under-over-display.over .under-over-text {
            background: rgba(253, 126, 20, 0.3);
            border-color: rgba(253, 126, 20, 0.5);
        }

        .winning-outcomes-section {
            width: 100%;
        }

        .outcomes-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 15px;
            max-height: 400px;
            overflow-y: auto;
            padding: 10px;
        }

        .outcome-card {
            background: rgba(255, 255, 255, 0.1);
            border: 2px solid rgba(255, 255, 255, 0.2);
            border-radius: 10px;
            padding: 20px;
            text-align: center;
            backdrop-filter: blur(5px);
            transition: all 0.3s ease;
        }

        .outcome-card:hover {
            transform: scale(1.05);
            border-color: rgba(255, 255, 255, 0.4);
            background: rgba(255, 255, 255, 0.15);
        }

        .outcome-name {
            font-size: 24px;
            font-weight: bold;
            color: #ffffff;
            margin-bottom: 10px;
            text-shadow: 2px 2px 4px rgba(0, 0, 0, 0.5);
        }

        .outcome-amount {
            font-size: 20px;
            color: #e6f3ff;
        }

        .no-outcomes-message {
            color: rgba(255, 255, 255, 0.7);
            font-size: 18px;
            text-align: center;
            padding: 20px;
            grid-column: 1 / -1;
        }
        
        .outcome-display {
            background: rgba(255, 255, 255, 0.2);
            border: 3px solid rgba(255, 255, 255, 0.4);
            border-radius: 15px;
            padding: 40px 60px;
            margin: 20px 0;
            position: relative;
            overflow: hidden;
            opacity: 0;
            transform: translateY(50px);
            animation: outcomeSlideIn 1.5s ease-out 1s forwards;
        }
        
        .outcome-display::before {
            content: '';
            position: absolute;
            top: -2px;
            left: -2px;
            right: -2px;
            bottom: -2px;
            background: linear-gradient(45deg, 
                transparent, rgba(255, 255, 255, 0.3), transparent,
                rgba(255, 255, 255, 0.3), transparent);
            border-radius: 15px;
            animation: shimmer 2s ease-in-out infinite;
            z-index: -1;
        }
        
        .outcome-text {
            font-size: 72px;
            font-weight: bold;
            color: #ffffff;
            text-shadow: 4px 4px 8px rgba(0, 0, 0, 0.6);
            text-align: center;
            letter-spacing: 4px;
            animation: textPulse 2s ease-in-out infinite;
        }
        
        .match-info {
            color: rgba(255, 255, 255, 0.9);
            font-size: 18px;
            text-align: center;
            margin-top: 25px;
            opacity: 0;
            animation: fadeInUp 1s ease-out 1.5s forwards;
        }
        
        .match-number {
            font-weight: bold;
            font-size: 22px;
            color: #ffffff;
        }
        
        .fighters {
            margin: 10px 0;
            font-size: 20px;
            color: #e6f3ff;
        }
        
        .winning-fighter {
            margin: 5px 0;
            font-size: 22px;
            font-weight: bold;
            color: #ffff99;
            text-shadow: 2px 2px 4px rgba(0, 0, 0, 0.8);
        }
        
        .venue {
            font-style: italic;
            color: #ccddff;
        }
        
        .celebration-effects {
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            pointer-events: none;
            overflow: hidden;
            z-index: -1;
        }
        
        .confetti {
            position: absolute;
            width: 10px;
            height: 10px;
            opacity: 0;
            animation: confettiFall 3s ease-out infinite;
        }
        
        .confetti:nth-child(odd) {
            background: rgba(255, 215, 0, 0.8);
            border-radius: 50%;
            animation-delay: 0.5s;
        }
        
        .confetti:nth-child(even) {
            background: rgba(255, 255, 255, 0.8);
            width: 8px;
            height: 12px;
            animation-delay: 1s;
        }
        
        .flash-effect {
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(255, 255, 255, 0.3);
            opacity: 0;
            border-radius: 20px;
            animation: flashEffect 0.5s ease-out 2s;
        }
        
        /* Outcome-specific styling */
        .outcome-win1 .outcome-display {
            border-color: rgba(40, 167, 69, 0.6);
            background: rgba(40, 167, 69, 0.2);
        }
        
        .outcome-win2 .outcome-display {
            border-color: rgba(220, 53, 69, 0.6);
            background: rgba(220, 53, 69, 0.2);
        }
        
        .outcome-draw .outcome-display {
            border-color: rgba(255, 193, 7, 0.6);
            background: rgba(255, 193, 7, 0.2);
        }
        
        .outcome-ko .outcome-display {
            border-color: rgba(220, 53, 69, 0.8);
            background: rgba(220, 53, 69, 0.3);
            animation: outcomeSlideIn 1.5s ease-out 1s forwards, koSpecial 0.5s ease-out 2.5s;
        }
        
        .outcome-pts .outcome-display {
            border-color: rgba(0, 123, 255, 0.6);
            background: rgba(0, 123, 255, 0.2);
        }
        
        .outcome-under .outcome-display {
            border-color: rgba(23, 162, 184, 0.6);
            background: rgba(23, 162, 184, 0.2);
        }
        
        .outcome-over .outcome-display {
            border-color: rgba(253, 126, 20, 0.6);
            background: rgba(253, 126, 20, 0.2);
        }
        
        /* Animations */
        @keyframes fadeInScale {
            0% {
                opacity: 0;
                transform: scale(0.8);
            }
            100% {
                opacity: 1;
                transform: scale(1);
            }
        }
        
        @keyframes titleBounce {
            0% {
                opacity: 0;
                transform: translateY(-30px);
            }
            60% {
                transform: translateY(5px);
            }
            100% {
                opacity: 1;
                transform: translateY(0);
            }
        }
        
        @keyframes outcomeSlideIn {
            0% {
                opacity: 0;
                transform: translateY(50px) scale(0.8);
            }
            70% {
                transform: translateY(-10px) scale(1.05);
            }
            100% {
                opacity: 1;
                transform: translateY(0) scale(1);
            }
        }
        
        @keyframes textPulse {
            0%, 100% {
                transform: scale(1);
                text-shadow: 4px 4px 8px rgba(0, 0, 0, 0.6);
            }
            50% {
                transform: scale(1.05);
                text-shadow: 4px 4px 12px rgba(0, 0, 0, 0.8), 0 0 20px rgba(255, 255, 255, 0.3);
            }
        }
        
        @keyframes fadeInUp {
            0% {
                opacity: 0;
                transform: translateY(20px);
            }
            100% {
                opacity: 1;
                transform: translateY(0);
            }
        }
        
        @keyframes shimmer {
            0% {
                transform: translateX(-100%);
            }
            100% {
                transform: translateX(200%);
            }
        }
        
        @keyframes confettiFall {
            0% {
                opacity: 1;
                transform: translateY(-100vh) rotate(0deg);
            }
            100% {
                opacity: 0;
                transform: translateY(100vh) rotate(360deg);
            }
        }
        
        @keyframes flashEffect {
            0%, 100% {
                opacity: 0;
            }
            50% {
                opacity: 0.6;
            }
        }
        
        @keyframes koSpecial {
            0% {
                transform: scale(1);
            }
            50% {
                transform: scale(1.1);
                box-shadow: 0 0 30px rgba(220, 53, 69, 0.8);
            }
            100% {
                transform: scale(1);
            }
        }
        
        /* Responsive Design */
        @media (max-width: 1200px) {
            .results-panel {
                padding: 40px;
                min-width: 500px;
                min-height: 300px;
            }
            
            .results-title {
                font-size: 30px;
            }
            
            .outcome-text {
                font-size: 60px;
            }
            
            .match-info {
                font-size: 16px;
            }
        }
        
        @media (max-width: 800px) {
            .results-panel {
                padding: 30px;
                min-width: 90%;
                min-height: 250px;
            }
            
            .results-title {
                font-size: 24px;
                margin-bottom: 20px;
            }
            
            .outcome-text {
                font-size: 48px;
                letter-spacing: 2px;
            }
            
            .outcome-display {
                padding: 30px 40px;
            }
            
            .match-info {
                font-size: 14px;
            }
            
            .match-number {
                font-size: 18px;
            }
            
            .fighters {
                font-size: 16px;
            }
        }
        
        /* Loading state styles */
        .loading-state {
            display: flex;
            align-items: center;
            justify-content: center;
            color: rgba(255, 255, 255, 0.7);
            font-size: 24px;
            font-weight: normal;
        }
        
        .loading-dots {
            display: inline-block;
            animation: loadingDots 1.5s infinite;
        }
        
        @keyframes loadingDots {
            0%, 20% { content: ''; }
            40% { content: '.'; }
            60% { content: '..'; }
            80%, 100% { content: '...'; }
        }
        
        .loading-dots::after {
            content: '';
            animation: loadingDots 1.5s infinite;
        }

        /* Match Info Section Styles */
        .match-info-section {
            text-align: center;
            margin-bottom: 30px;
            width: 100%;
        }

        .match-title {
            color: white;
            font-size: 48px;
            font-weight: bold;
            text-align: center;
            margin-bottom: 40px;
            text-shadow: 3px 3px 6px rgba(0, 0, 0, 0.5);
            opacity: 0;
            animation: titleBounce 2s ease-out 0.5s forwards;
        }

        .fighters-display {
            margin: 30px 0;
            opacity: 0;
            animation: fadeInUp 1s ease-out 1s forwards;
        }

        .fighter-names {
            font-size: 64px;
            font-weight: bold;
            color: #ffffff;
            text-shadow: 4px 4px 8px rgba(0, 0, 0, 0.6);
            letter-spacing: 2px;
            text-align: center;
            line-height: 1.2;
        }

        .venue-info {
            color: rgba(255, 255, 255, 0.9);
            font-size: 24px;
            font-style: italic;
            margin-top: 20px;
            opacity: 0;
            animation: fadeInUp 1s ease-out 1.5s forwards;
        }

        /* Winning Bets Section Styles */
        .winning-bets-section {
            width: 100%;
            margin-top: 20px;
        }

        .bets-title {
            color: white;
            font-size: 36px;
            font-weight: bold;
            text-align: center;
            margin-bottom: 20px;
            text-shadow: 3px 3px 6px rgba(0, 0, 0, 0.5);
            opacity: 0;
            animation: titleBounce 2s ease-out 5.5s forwards;
        }

        .bets-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 15px;
            max-height: 300px;
            overflow-y: auto;
            padding: 10px;
            opacity: 0;
            animation: fadeInUp 1s ease-out 6s forwards;
        }

        .bet-card {
            background: rgba(255, 255, 255, 0.1);
            border: 2px solid rgba(255, 255, 255, 0.2);
            border-radius: 10px;
            padding: 15px;
            text-align: center;
            backdrop-filter: blur(5px);
            transition: all 0.3s ease;
        }

        .bet-card:hover {
            transform: scale(1.05);
            border-color: rgba(255, 255, 255, 0.4);
            background: rgba(255, 255, 255, 0.15);
        }

        .bet-outcome {
            font-size: 18px;
            font-weight: bold;
            color: #ffffff;
            margin-bottom: 8px;
            text-shadow: 2px 2px 4px rgba(0, 0, 0, 0.5);
        }

        .bet-amount {
            font-size: 16px;
            color: #e6f3ff;
        }

        .bet-win-amount {
            font-size: 20px;
            font-weight: bold;
            color: #ffff99;
            margin-top: 5px;
            text-shadow: 2px 2px 4px rgba(0, 0, 0, 0.8);
        }

        .no-bets-message {
            color: rgba(255, 255, 255, 0.7);
            font-size: 18px;
            text-align: center;
            padding: 20px;
            grid-column: 1 / -1;
        }

        /* Combined Result Display */
        .combined-result-display {
            text-align: center;
            margin-bottom: 30px;
        }

        .combined-result-text {
            font-size: 60px;
            font-weight: bold;
            color: #ffffff;
            text-shadow: 4px 4px 8px rgba(0, 0, 0, 0.6);
            letter-spacing: 4px;
            text-align: center;
            background: rgba(255, 255, 255, 0.1);
            border-radius: 15px;
            padding: 20px 40px;
            border: 3px solid rgba(255, 255, 255, 0.3);
            display: inline-block;
            min-width: 400px;
        }

        /* Winning Bets Section */
        .winning-bets-section {
            width: 100%;
            margin-top: 20px;
        }

        .bets-title {
            color: white;
            font-size: 32px;
            font-weight: bold;
            text-align: center;
            margin-bottom: 20px;
            text-shadow: 3px 3px 6px rgba(0, 0, 0, 0.5);
        }

        .bets-list {
            display: flex;
            flex-wrap: wrap;
            justify-content: center;
            gap: 15px;
            max-height: 300px;
            overflow-y: auto;
            padding: 10px;
        }

        .bet-item {
            background: rgba(255, 255, 255, 0.1);
            border: 2px solid rgba(255, 255, 255, 0.2);
            border-radius: 10px;
            padding: 15px;
            text-align: center;
            backdrop-filter: blur(5px);
            transition: all 0.3s ease;
            min-width: 150px;
        }

        .bet-item:hover {
            transform: scale(1.05);
            border-color: rgba(255, 255, 255, 0.4);
            background: rgba(255, 255, 255, 0.15);
        }

        .bet-outcome {
            font-size: 18px;
            font-weight: bold;
            color: #ffffff;
            margin-bottom: 8px;
            text-shadow: 2px 2px 4px rgba(0, 0, 0, 0.5);
        }

        .bet-amount {
            font-size: 16px;
            color: #e6f3ff;
        }
    </style>
</head>
<body>
    <div class="overlay-container">
        <div class="results-panel" id="resultsPanel">
            <div class="results-content" id="resultsContent">
                <!-- Title -->
                <div class="results-title">RESULTS</div>

                <!-- Fighters Display -->
                <div class="fighters-display" id="fightersDisplay">
                    <div class="fighter-names" id="fighterNames">
                        <span id="fighter1">Fighter 1</span> VS <span id="fighter2">Fighter 2</span>
                    </div>
                </div>

                <!-- Combined Result Display -->
                <div class="combined-result-display" id="combinedResultDisplay">
                    <div class="combined-result-text" id="combinedResultText">
                        <span id="mainResult">WIN1</span>
                    </div>
                </div>

                <!-- Winning Bets Section -->
                <div class="winning-bets-section">
                    <div class="bets-title">Winning bets:</div>
                    <div class="bets-list" id="betsList">
                        <!-- Winning bets will be populated here -->
                    </div>
                </div>
            </div>
        </div>
    </div>

    <script>
        // Global variables for overlay data handling
        let overlayData = {};
        let currentMainResult = 'WIN1';
        let currentUnderOverResult = 'UNDER';
        let currentMatch = null;
        let winningOutcomes = [];
        let animationStarted = false;
        let videoStarted = false;
        let contentVisible = false;
        let videoStartTime = null;
        let contentDelayTimer = null;
        let resultsTimer = null;
        let lastPositionLogTime = 0;
        const POSITION_LOG_THROTTLE_MS = 500; // Throttle position logs to max 1 per 500ms

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


        // 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 results data functions
        async function fetchResultsData(retryCount = 0) {
            const maxRetries = 10;
            const baseDelay = 1000; // 1 second

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

                // Check if WebChannel is available
                if (!window.overlay || typeof window.overlay.getCurrentData !== 'function') {
                    if (retryCount < maxRetries) {
                        const delay = baseDelay * Math.pow(2, retryCount);
                        setTimeout(() => {
                            fetchResultsData(retryCount + 1);
                        }, delay);
                    } else {
                        debugTime('Max retries reached for WebChannel connection');
                        showFallbackResults();
                    }
                    return;
                }

                // Call WebChannel method to get current overlay data
                const currentDataJson = await window.overlay.getCurrentData();

                let data;
                try {
                    data = JSON.parse(currentDataJson);
                } catch (parseError) {
                    throw new Error(`JSON parse error: ${parseError.message}`);
                }

                debugTime('Results data received via WebChannel');

                if (data && (data.outcome || data.result)) {
                    updateOverlayData(data);
                } else {
                    debugTime('No results data in WebChannel response');
                    // Keep checking for data
                    setTimeout(() => fetchResultsData(0), 1000);
                }
            } catch (error) {
                debugTime(`Failed to fetch results data: ${error.message}`);

                // Check if we should retry
                if (retryCount < maxRetries) {
                    // Calculate delay with exponential backoff
                    const delay = baseDelay * Math.pow(2, retryCount);

                    setTimeout(() => {
                        fetchResultsData(retryCount + 1);
                    }, delay);
                } else {
                    debugTime('Max retries reached for results data fetch');
                    // Show fallback data instead of error message
                    showFallbackResults();
                }
            }
        }

        // 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(`[RESULTS] ${message}`);
                    }
                }
            } catch (e) {
                // Fallback to console if WebChannel not available - use original console to avoid recursion
                originalConsoleLog(`[RESULTS FALLBACK] ${message}`);
            }
        }

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

        // Setup WebChannel communication
        function setupWebChannel() {
            // Check if WebChannel is already set up by overlay.js
            if (window.overlay) {
                // Listen for data updates from Python
                if (window.overlay.dataUpdated) {
                    window.overlay.dataUpdated.connect(function(data) {
                        if (data && (data.outcome || data.result)) {
                            updateOverlayData(data);
                        }
                    });
                }

                // Connect positionChanged signal
                if (window.overlay.positionChanged) {
                    window.overlay.positionChanged.connect(function(position, duration) {
                        if (position !== null && duration !== null) {
                            handlePositionChange(position, duration);
                        }
                    });
                }

                webChannelReady = 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) {
                        // 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) {
                                if (data && (data.outcome || data.result)) {
                                    updateOverlayData(data);
                                }
                            });
                        }

                        // Connect positionChanged signal
                        if (window.overlay && window.overlay.positionChanged) {
                            window.overlay.positionChanged.connect(function(position, duration) {
                                if (position !== null && duration !== null) {
                                    handlePositionChange(position, duration);
                                }
                            });
                        }

                        webChannelReady = true;
                    });
                } catch (e) {
                }
            }
        }

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

        // Show fallback results data when API is not available yet
        function showFallbackResults() {
            const fallbackData = {
                outcome: 'WIN1',
                under_over_result: 'OVER',
                match: {
                    fighter1_township: 'Fallback Fighter 1',
                    fighter2_township: 'Fallback Fighter 2'
                },
                match_id: 1
            };
            updateOverlayData(fallbackData);
        }

        // Outcome categories for styling
        const outcomeCategories = {
            'WIN1': 'win1',
            'WIN2': 'win2',
            'X': 'draw',
            'DRAW': 'draw',
            'DKO': 'draw',
            'KO1': 'ko',
            'KO2': 'ko',
            'PTS1': 'pts',
            'PTS2': 'pts',
            'RET1': 'pts',
            'RET2': 'pts',
            'UNDER': 'under',
            'OVER': 'over'
        };

        // Function to update overlay data (called by Qt WebChannel)
        function updateOverlayData(data) {
            overlayData = data || {};

            // Only update if we have valid data
            if (data && (data.outcome || data.result)) {
                let result = data.outcome || data.result;
                console.log('RESULTS TEMPLATE: Processing valid result:', result);

                // Check if this is the same data we already processed (prevent duplicate processing)
                const dataHash = JSON.stringify(data);
                if (window.lastProcessedDataHash === dataHash) {
                    return;
                }
                window.lastProcessedDataHash = dataHash;

                // Always treat the main result as the primary outcome
                currentMainResult = result;

                // Check if under/over result is provided separately
                if (data.under_over_result) {
                    currentUnderOverResult = data.under_over_result;
                } else {
                    // Fallback: determine if main result is under/over
                    if (result === 'UNDER' || result === 'OVER') {
                        currentUnderOverResult = result;
                        currentMainResult = null; // No separate main result when under/over is the main result
                    } else {
                        currentUnderOverResult = null; // No under/over result
                    }
                }

                if (data.match) {
                    currentMatch = data.match;
                }

                if (data.match_id) {
                    // Fetch winning outcomes for this match
                    fetchWinningOutcomes(data.match_id);

                    // Check if results have already been shown for this match (handles overlay reloads)
                    const resultsShownKey = 'results_shown_' + data.match_id;
                    const alreadyShown = sessionStorage.getItem(resultsShownKey) === 'true';
                    if (alreadyShown) {
                        contentVisible = true;
                        showResultsPanel();
                        showResultsContent();
                        return; // Don't prepare animation again
                    }
                }

                // Prepare data and start 5-second timer to show results
                prepareResultsAnimation();

            } else {
                // Keep trying to fetch data
                setTimeout(() => fetchResultsData(0), 1000);
            }
        }

        // Prepare the results animation sequence (called when data is received)
        function prepareResultsAnimation() {
            if (animationStarted) return;
            animationStarted = true;

            // Update fighters display
            updateFightersDisplay();

            // Update combined result display
            updateCombinedResultDisplay();

            // Update winning bets display
            updateWinningBetsDisplay();

            // Show blue background after 5 seconds from data receipt
            setTimeout(() => {
                if (!contentVisible) {
                    // Mark results as shown in sessionStorage
                    if (overlayData && overlayData.match_id) {
                        sessionStorage.setItem('results_shown_' + overlayData.match_id, 'true');
                    }

                    showResultsPanel(); // Show blue background

                    // Show data immediately after background appears
                    setTimeout(() => {
                        contentVisible = true;
                        showResultsContent();
                    }, 100); // Small delay to ensure background is visible first
                }
            }, 5000);
        }

        // Fetch winning outcomes for the match
        function fetchWinningOutcomes(matchId) {
            // Use Qt WebChannel to request winning outcomes data
            if (window.overlay && window.overlay.getWinningOutcomes) {
                try {
                    const outcomesJson = window.overlay.getWinningOutcomes(matchId);
                    const outcomesData = JSON.parse(outcomesJson);
                    winningOutcomes = outcomesData || [];
                    updateWinningBetsDisplay();
                } catch (error) {
                    // Fallback: show sample data for testing
                    winningOutcomes = [
                        { outcome: 'WIN1', amount: 125.00 },
                        { outcome: 'OVER', amount: 87.50 },
                        { outcome: 'KO1', amount: 95.00 }
                    ];
                    updateWinningBetsDisplay();
                }
            } else {
                // Fallback: show sample data for testing
                winningOutcomes = [
                    { outcome: 'WIN1', amount: 125.00 },
                    { outcome: 'OVER', amount: 87.50 },
                    { outcome: 'KO1', amount: 95.00 }
                ];
                updateWinningBetsDisplay();
            }
        }

        // Show results panel with fade-in animation
        function showResultsPanel() {
            const resultsPanel = document.getElementById('resultsPanel');
            if (resultsPanel) {
                resultsPanel.classList.add('visible');
            }
        }

        // Show results content with animation after delay
        function showResultsContent() {
            const resultsContent = document.getElementById('resultsContent');
            if (resultsContent) {
                resultsContent.classList.add('visible');
            }
        }

        // Handle video position changes (for logging/debugging purposes)
        function handlePositionChange(position, duration) {
            const currentTime = Date.now();

            // Check if video has started playing (position > 0)
            if (position > 0 && !videoStarted) {
                videoStarted = true;
            }

            // Check if we've reached 5 seconds and should show results
            if (position >= 5 && !contentVisible && overlayData && (overlayData.outcome || overlayData.result)) {
                contentVisible = true;
                showResultsPanel();
                showResultsContent();
            }

            // Throttle position logging to reduce message bus traffic
            if (currentTime - lastPositionLogTime >= POSITION_LOG_THROTTLE_MS) {
                lastPositionLogTime = currentTime;
            }
        }

        // Update fighters display
        function updateFightersDisplay() {
            if (!currentMatch) {
                return;
            }

            const fighter1 = document.getElementById('fighter1');
            const fighter2 = document.getElementById('fighter2');

            // Update fighter names
            if (currentMatch) {
                fighter1.textContent = currentMatch.fighter1_township || 'Fighter 1';
                fighter2.textContent = currentMatch.fighter2_township || 'Fighter 2';
            }
        }

        // Update combined result display
        function updateCombinedResultDisplay() {
            const mainResultSpan = document.getElementById('mainResult');
            const combinedDisplay = document.getElementById('combinedResultDisplay');

            if (currentMainResult) {
                mainResultSpan.textContent = currentMainResult;
                combinedDisplay.style.display = 'block';
            } else {
                combinedDisplay.style.display = 'none';
            }
        }

        // Update winning bets display with staggered animation
        function updateWinningBetsDisplay() {
            const betsList = document.getElementById('betsList');
            betsList.innerHTML = '';

            if (!winningOutcomes || winningOutcomes.length === 0) {
                const noBetsDiv = document.createElement('div');
                noBetsDiv.className = 'no-bets-message';
                noBetsDiv.textContent = 'No winning bets for this match';
                betsList.appendChild(noBetsDiv);
                return;
            }

            // Create bet items for each winning outcome with staggered animation
            winningOutcomes.forEach((outcome, index) => {
                const betItem = document.createElement('div');
                betItem.className = 'bet-item';
                betItem.style.opacity = '0';
                betItem.style.transform = 'translateY(20px)';

                betItem.innerHTML = `
                    <div class="bet-outcome">${outcome.outcome || 'Unknown'}</div>
                `;

                betsList.appendChild(betItem);

                // Animate in with delay (staggered by 200ms)
                setTimeout(() => {
                    betItem.style.transition = 'all 0.5s ease-out';
                    betItem.style.opacity = '1';
                    betItem.style.transform = 'translateY(0)';
                }, index * 200);
            });
        }

        // Generate confetti effects
        function generateConfetti() {
            const celebrationEffects = document.getElementById('celebrationEffects');
            celebrationEffects.innerHTML = '';

            for (let i = 0; i < 50; i++) {
                const confetti = document.createElement('div');
                confetti.className = 'confetti';
                confetti.style.left = Math.random() * 100 + '%';
                confetti.style.animationDelay = Math.random() * 3 + 's';
                confetti.style.animationDuration = (Math.random() * 2 + 2) + 's';
                celebrationEffects.appendChild(confetti);
            }
        }

        // Restart animations
        function restartAnimations() {
            const resultsPanel = document.getElementById('resultsPanel');

            // Reset animations by removing and re-adding classes
            resultsPanel.style.animation = 'none';
            resultsPanel.offsetHeight; // Trigger reflow
            resultsPanel.style.animation = null;
        }

        // Set outcome for testing/demo
        function setOutcome(outcome, matchData = null) {
            if (outcome) {
                currentOutcome = outcome;
                if (matchData) {
                    currentMatch = matchData;
                }
                showResultsPanel();
                updateResultsDisplay();
            } else {
                showLoadingState();
            }
        }

        // Initialize when DOM is loaded
        document.addEventListener('DOMContentLoaded', function() {
            startTime = Date.now();
            debugTime('DOM Content Loaded - Starting results overlay initialization');

            // Setup WebChannel first
            setupWebChannel();

            // Show initial state

            // Wait briefly for WebChannel to connect
            setTimeout(() => {
                // Fetch results data via WebChannel
                debugTime('Fetching results data via WebChannel');
                fetchResultsData();

                // Set up periodic refresh every 30 seconds
                setInterval(() => {
                    fetchResultsData(0); // Start with retry count 0 for periodic refreshes
                }, 30000);

                // Show fallback if no data after 5 seconds total
                setTimeout(() => {
                    if (!contentVisible) {
                        debugTime('No data received after 5 seconds - showing fallback');
                        showFallbackResults();
                    }
                }, 5000);
            }, 50); // Wait 50ms for WebChannel setup
        });

        // Export functions for external use
        window.setOutcome = setOutcome;
        window.updateOverlayData = updateOverlayData;
    </script>

    <!--
    IMPORTANT: When creating or editing custom templates, always maintain this script tag:
    1. qrc:///qtwebchannel/qwebchannel.js - Required for Qt WebChannel communication

    This script enables communication between the Qt application and the overlay template.
    The results.html template uses inline WebChannel setup with client-initiated data fetching,
    similar to fixtures.html, and includes custom dataUpdated signal handling.

    NOTE: When editing this template, never remove the qrc:///qtwebchannel/qwebchannel.js script source!
    The template implements its own WebChannel setup and data polling mechanism.
    -->
</body>
</html>
