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

        /* Top right timer */
        .timer-container {
            position: absolute;
            top: 20px;
            right: 20px;
            background: rgba(0, 123, 255, 0.8);
            color: white;
            padding: 12px 18px;
            border-radius: 8px;
            font-size: 32px;
            font-weight: bold;
            font-family: 'Courier New', monospace;
            border: 2px solid rgba(255, 255, 255, 0.3);
            z-index: 1000;
            min-width: 140px;
            text-align: center;
        }

        /* Bottom info bar */
        .info-bar {
            position: absolute;
            bottom: 0;
            left: 0;
            right: 0;
            background: rgba(0, 123, 255, 0.8);
            backdrop-filter: blur(10px);
            border-top: 2px solid rgba(255, 255, 255, 0.3);
            padding: 20px;
            z-index: 1000;
        }

        .fighter-names {
            color: white;
            font-size: 36px;
            font-weight: bold;
            text-align: center;
            margin-bottom: 8px;
            text-shadow: 2px 2px 4px rgba(0, 0, 0, 0.8);
        }

        .venue-info {
            color: rgba(255, 255, 255, 0.95);
            font-size: 28px;
            text-align: center;
            font-style: italic;
            text-shadow: 1px 1px 2px rgba(0, 0, 0, 0.8);
        }

        /* Result indicator (optional) */
        .result-indicator {
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            background: rgba(255, 0, 0, 0.9);
            color: white;
            padding: 20px 40px;
            border-radius: 15px;
            font-size: 36px;
            font-weight: bold;
            text-align: center;
            border: 3px solid rgba(255, 255, 255, 0.8);
            z-index: 1001;
            display: none;
            animation: resultPulse 2s ease-in-out infinite;
        }

        @keyframes resultPulse {
            0% { transform: translate(-50%, -50%) scale(1); }
            50% { transform: translate(-50%, -50%) scale(1.1); }
            100% { transform: translate(-50%, -50%) scale(1); }
        }

        /* Entrance animation for fighter names */
        .entrance-animation {
            position: fixed;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            color: white;
            font-size: 72px;
            font-weight: bold;
            text-align: center;
            text-shadow: 4px 4px 8px rgba(0, 0, 0, 0.9);
            z-index: 2000;
            opacity: 0;
            animation: entranceFadeIn 1s ease-out forwards, entranceFadeOut 1s ease-in 5s forwards;
            pointer-events: none;
        }

        @keyframes entranceFadeIn {
            0% {
                opacity: 0;
                transform: translate(-50%, -50%) scale(0.8);
            }
            100% {
                opacity: 1;
                transform: translate(-50%, -50%) scale(1);
            }
        }

        @keyframes entranceFadeOut {
            0% {
                opacity: 1;
                transform: translate(-50%, -50%) scale(1);
            }
            100% {
                opacity: 0;
                transform: translate(-50%, -50%) scale(0.8);
            }
        }

        /* Fight! animation */
        .fight-animation {
            position: fixed;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            color: #ff4444;
            font-size: 96px;
            font-weight: bold;
            text-align: center;
            text-shadow: 6px 6px 12px rgba(0, 0, 0, 0.9);
            z-index: 2001;
            opacity: 0;
            animation: fightFadeIn 0.2s ease-out forwards, fightHold 0.8s ease-in 0.2s forwards, fightFadeOut 0.5s ease-in 1.0s forwards;
        }

        @keyframes fightFadeIn {
            0% {
                opacity: 0;
                transform: translate(-50%, -50%) scale(0.5);
            }
            100% {
                opacity: 1;
                transform: translate(-50%, -50%) scale(1.2);
            }
        }

        @keyframes fightHold {
            0% {
                opacity: 1;
                transform: translate(-50%, -50%) scale(1.2);
            }
            100% {
                opacity: 1;
                transform: translate(-50%, -50%) scale(1.2);
            }
        }

        @keyframes fightFadeOut {
            0% {
                opacity: 1;
                transform: translate(-50%, -50%) scale(1.2);
            }
            100% {
                opacity: 0;
                transform: translate(-50%, -50%) scale(0.8);
            }
        }

        /* Responsive design */
        @media (max-width: 1200px) {
            .fighter-names {
                font-size: 30px;
            }
            .venue-info {
                font-size: 24px;
            }
            .timer-container {
                font-size: 28px;
                padding: 10px 14px;
                min-width: 130px;
            }
            .entrance-animation {
                font-size: 60px;
            }
            .fight-animation {
                font-size: 80px;
            }
        }

        @media (max-width: 800px) {
            .fighter-names {
                font-size: 24px;
            }
            .venue-info {
                font-size: 20px;
            }
            .timer-container {
                font-size: 24px;
                padding: 8px 12px;
                top: 10px;
                right: 10px;
                min-width: 120px;
            }
            .info-bar {
                padding: 15px;
            }
            .entrance-animation {
                font-size: 48px;
            }
            .fight-animation {
                font-size: 64px;
            }
        }
    </style>
</head>
<body>
    <!-- Timer in top right -->
    <div class="timer-container" id="matchTimer">
        00:00
    </div>

    <!-- Entrance animation for fighter names -->
    <div class="entrance-animation" id="entranceAnimation" style="display: none;">
        <div id="entranceFighterNames">Fighter 1 vs Fighter 2</div>
    </div>

    <!-- Fight! animation -->
    <div class="fight-animation" id="fightAnimation" style="display: none;">
        <div id="fightText">Fight!</div>
    </div>

    <!-- Result indicator (shown briefly at end) -->
    <div class="result-indicator" id="resultIndicator">
        <div id="resultText">RESULT</div>
    </div>

    <!-- Bottom info bar -->
    <div class="info-bar">
        <div class="fighter-names" id="fighterNames">Loading fighters...</div>
        <div class="venue-info" id="venueInfo">Loading venue...</div>
    </div>

    <script>
        // Global variables for overlay data handling
        let overlayData = {};
        let fixturesData = null;
        let matchData = null;
        let videoDuration = 0;
        let timerInterval = null;
        let currentTime = 0;
        let webServerBaseUrl = 'http://127.0.0.1:5001';
        let webServerUrlReceived = false;
        let entranceAnimationShown = false;  // Flag to prevent re-showing entrance animation

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

        // Function to update overlay data (called by Qt WebChannel)
        function updateOverlayData(data) {
            console.log('Match video overlay received data:', data);
            overlayData = data || {};

            // Update web server base URL if provided
            if (data && data.webServerBaseUrl) {
                webServerBaseUrl = data.webServerBaseUrl;
                webServerUrlReceived = true;
                console.log('Updated web server base URL:', webServerBaseUrl);
            }

            // Extract match data
            if (data && data.match) {
                const hadMatchData = !!matchData;
                matchData = data.match;
                updateMatchInfo();
                // Only show entrance animation if not already shown and this is first match data
                if (!hadMatchData && !entranceAnimationShown) {
                    console.log('DEBUG: [MATCH_VIDEO] Match data received via WebChannel, showing entrance animation');
                    showEntranceAnimation();
                }
            }

            // Extract video duration if provided
            if (data && data.video_duration) {
                videoDuration = parseFloat(data.video_duration) || 0;
                console.log('Video duration set to:', videoDuration, 'seconds');
            }

            // Extract result if provided
            if (data && data.result) {
                showResult(data.result);
            }
        }

        // Update match information display
        function updateMatchInfo() {
            if (!matchData) return;

            const fighterNames = document.getElementById('fighterNames');
            const venueInfo = document.getElementById('venueInfo');

            // Get fighter names
            const fighter1 = matchData.fighter1_township || matchData.fighter1 || 'Fighter 1';
            const fighter2 = matchData.fighter2_township || matchData.fighter2 || 'Fighter 2';

            fighterNames.textContent = `${fighter1} vs ${fighter2}`;

            // Get venue
            const venue = matchData.venue_kampala_township || matchData.venue || 'Venue TBA';
            venueInfo.textContent = venue;

            console.log('Updated match info:', { fighters: `${fighter1} vs ${fighter2}`, venue: venue });
        }

        // Start match timer
        function startTimer() {
            if (timerInterval) {
                clearInterval(timerInterval);
            }

            currentTime = 0;
            updateTimerDisplay();

            timerInterval = setInterval(() => {
                currentTime++;
                updateTimerDisplay();

                // Check if we've reached video duration
                if (videoDuration > 0 && currentTime >= videoDuration) {
                    stopTimer();
                    onVideoEnd();
                }
            }, 1000);
        }

        // Stop match timer
        function stopTimer() {
            if (timerInterval) {
                clearInterval(timerInterval);
                timerInterval = null;
            }
        }

        // Update timer display
        function updateTimerDisplay() {
            const minutes = Math.floor(currentTime / 60);
            const seconds = currentTime % 60;
            const timeString = `${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`;
            document.getElementById('matchTimer').textContent = timeString;
        }

        // Handle video end
        function onVideoEnd() {
            console.log('Video ended, showing result');
            if (overlayData && overlayData.result) {
                showResult(overlayData.result);
            }
        }

        // Show result indicator
        function showResult(result) {
            const resultIndicator = document.getElementById('resultIndicator');
            const resultText = document.getElementById('resultText');

            resultText.textContent = result.toUpperCase();
            resultIndicator.style.display = 'block';

            // Hide after 5 seconds
            setTimeout(() => {
                resultIndicator.style.display = 'none';
            }, 5000);
        }

        // Fetch fixture data using WebChannel instead of API fetch
        async function fetchFixtureData() {
            try {
                console.log('DEBUG: [MATCH_VIDEO] Attempting to get fixture data from WebChannel');
                console.log('DEBUG: [MATCH_VIDEO] window.overlay exists:', !!window.overlay);
                console.log('DEBUG: [MATCH_VIDEO] 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_VIDEO] Received fixture data from WebChannel:', fixtureJson);

                    if (fixtureJson) {
                        try {
                            fixturesData = JSON.parse(fixtureJson);
                            console.log('DEBUG: [MATCH_VIDEO] Parsed fixture data:', fixturesData);
                            console.log('DEBUG: [MATCH_VIDEO] fixturesData.length:', fixturesData ? fixturesData.length : 'null');

                            if (fixturesData && fixturesData.length > 0) {
                                console.log('DEBUG: [MATCH_VIDEO] WebChannel returned fixture data, calling updateMatchInfo()');
                                updateMatchInfoFromFixtures();
                            } else {
                                console.log('DEBUG: [MATCH_VIDEO] WebChannel returned empty fixture data');
                            }
                        } catch (parseError) {
                            console.log('DEBUG: [MATCH_VIDEO] Failed to parse fixture data from WebChannel:', parseError);
                        }
                    } else {
                        console.log('DEBUG: [MATCH_VIDEO] WebChannel returned null/empty fixture data');
                    }
                } else {
                    console.log('DEBUG: [MATCH_VIDEO] WebChannel overlay.getFixtureData not available');
                    console.log('DEBUG: [MATCH_VIDEO] window object keys:', Object.keys(window));
                    if (window.overlay) {
                        console.log('DEBUG: [MATCH_VIDEO] window.overlay keys:', Object.keys(window.overlay));
                    }
                }
            } catch (error) {
                console.log('DEBUG: [MATCH_VIDEO] Exception caught in fetchFixtureData');
                console.log('DEBUG: [MATCH_VIDEO] Error message =', error.message);
                console.log('DEBUG: [MATCH_VIDEO] Error stack =', error.stack);
            }
        }

        // Update match info from fixtures data
        function updateMatchInfoFromFixtures() {
            if (!fixturesData || fixturesData.length === 0) return;

            // Get the first match (should be the current match being played)
            const currentMatch = fixturesData[0];
            console.log('DEBUG: [MATCH_VIDEO] Using match data from fixtures:', currentMatch);

            if (currentMatch) {
                const hadMatchData = !!matchData;
                matchData = currentMatch;
                updateMatchInfo();

                // Show entrance animation only on first match data load, not on periodic refreshes
                if (!hadMatchData && !entranceAnimationShown) {
                    console.log('DEBUG: [MATCH_VIDEO] First match data received, showing entrance animation');
                    showEntranceAnimation();
                }
            }
        }

        // Show entrance animation with fighter names
        function showEntranceAnimation() {
            if (!matchData) return;

            const entranceElement = document.getElementById('entranceAnimation');
            const entranceText = document.getElementById('entranceFighterNames');

            // Get fighter names
            const fighter1 = matchData.fighter1_township || matchData.fighter1 || 'Fighter 1';
            const fighter2 = matchData.fighter2_township || matchData.fighter2 || 'Fighter 2';

            entranceText.textContent = `${fighter1} vs ${fighter2}`;
            entranceElement.style.display = 'block';

            // Mark that entrance animation has been shown
            entranceAnimationShown = true;

            console.log('DEBUG: [MATCH_VIDEO] Showing entrance animation for:', `${fighter1} vs ${fighter2}`);

            // Animation will automatically hide after 6 seconds (5s display + 1s fade out)
            setTimeout(() => {
                entranceElement.style.display = 'none';
                console.log('DEBUG: [MATCH_VIDEO] Entrance animation completed');

                // Start the "Fight!" animation after entrance animation completes
                setTimeout(() => {
                    showFightAnimation();
                }, 100); // Small delay to ensure entrance animation is fully hidden
            }, 6000);
        }

        // Show "Fight!" animation
        function showFightAnimation() {
            const fightElement = document.getElementById('fightAnimation');
            const fightText = document.getElementById('fightText');

            fightText.textContent = 'Fight!';
            fightElement.style.display = 'block';

            console.log('DEBUG: [MATCH_VIDEO] Showing Fight! animation');

            // Animation will automatically hide after 1.5 seconds (0.2s fade in + 0.8s display + 0.5s fade out)
            setTimeout(() => {
                fightElement.style.display = 'none';
                console.log('DEBUG: [MATCH_VIDEO] Fight! animation completed');
            }, 1500);
        }

        // Setup WebChannel communication
        function setupWebChannel() {
            // Check if WebChannel is already set up by overlay.js
            if (window.overlay) {
                console.log('DEBUG: [MATCH_VIDEO] 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: [MATCH_VIDEO] Received data update from Python:', data);
                        if (data && data.webServerBaseUrl) {
                            webServerBaseUrl = data.webServerBaseUrl;
                            webServerUrlReceived = true;
                            console.log('DEBUG: [MATCH_VIDEO] 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: [MATCH_VIDEO] Document ready, starting data fetch after URL update');
                                fetchFixtureData();
                            }
                        }
                        if (data && data.debugMode) {
                            console.log('DEBUG: [MATCH_VIDEO] Debug mode enabled');
                        }
                        if (data && data.timer_update) {
                            console.log('DEBUG: [MATCH_VIDEO] Timer update received:', data.timer_update);
                        }
                    });
                }
                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: [MATCH_VIDEO] 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: [MATCH_VIDEO] Received data update from Python:', data);
                                if (data && data.webServerBaseUrl) {
                                    webServerBaseUrl = data.webServerBaseUrl;
                                    webServerUrlReceived = true;
                                    console.log('DEBUG: [MATCH_VIDEO] Web server base URL updated to:', webServerBaseUrl);
                                }
                            });
                        } else {
                            console.log('DEBUG: [MATCH_VIDEO] Overlay object not available in WebChannel');
                        }
                    });
                } catch (e) {
                    console.log('DEBUG: [MATCH_VIDEO] Failed to setup WebChannel:', e);
                }
            } else {
                console.log('DEBUG: [MATCH_VIDEO] WebChannel not available, using default webServerBaseUrl');
            }
        }

        // Initialize when DOM is loaded
        document.addEventListener('DOMContentLoaded', function() {
            console.log('Match video overlay initialized');

            // Setup WebChannel first
            setupWebChannel();

            // Start timer immediately (will be synced with video)
            startTimer();

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

                // Fetch fixture data directly from WebChannel
                console.log('DEBUG: [MATCH_VIDEO] Starting fixture data fetch via WebChannel');
                fetchFixtureData();

                // Set up periodic refresh every 30 seconds
                setTimeout(function refreshData() {
                    console.log('DEBUG: [MATCH_VIDEO] Periodic refresh: fetching updated fixture data');
                    fetchFixtureData();
                    setTimeout(refreshData, 30000);
                }, 30000);

                // Fallback: Check if we have match data and show animation after 2 seconds
                setTimeout(() => {
                    if (matchData && !entranceAnimationShown) {
                        console.log('DEBUG: [MATCH_VIDEO] Fallback: Match data available, showing entrance animation');
                        showEntranceAnimation();
                    }
                }, 2000);

                // Show no matches if no data after 5 seconds total
                setTimeout(() => {
                    if (!matchData) {
                        console.log('DEBUG: [MATCH_VIDEO] No match data received after 5 seconds');
                    }
                }, 5000);
            }, 50); // Wait 50ms for WebChannel setup
        });

        // Cleanup on page unload
        window.addEventListener('beforeunload', function() {
            stopTimer();
        });
    </script>

    <!-- Required scripts for Qt WebChannel communication -->
    <script src="qrc:///qtwebchannel/qwebchannel.js"></script>
    <script src="overlay://overlay.js"></script>
</body>
</html>