<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>Fixtures 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 to verify CSS is loaded */
        body::before {
            content: 'Fixtures Overlay v1.0 loaded';
            position: absolute;
            top: 5px;
            left: 5px;
            color: rgba(255,255,255,0.5);
            font-size: 10px;
            z-index: 9999;
        }
        
        .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.40);
            border-radius: 20px;
            padding: 30px;
            max-width: 90%;
            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;
        }
        
        .fixtures-title {
            color: white;
            font-size: 28px;
            font-weight: bold;
            text-align: center;
            margin-bottom: 25px;
            text-shadow: 2px 2px 4px rgba(0, 0, 0, 0.5);
        }
        
        .fixtures-table {
            width: 100%;
            border-collapse: collapse;
            color: white;
            font-size: 16px;
            background: transparent;
        }
        
        .fixtures-table th {
            padding: 15px 10px;
            text-align: center;
            background: rgba(255, 255, 255, 0.1);
            font-weight: bold;
            font-size: 14px;
            text-transform: uppercase;
            letter-spacing: 1px;
            border-radius: 8px;
            margin: 2px;
            text-shadow: 1px 1px 2px rgba(0, 0, 0, 0.5);
        }
        
        .fixtures-table td {
            padding: 12px 10px;
            text-align: center;
            background: rgba(255, 255, 255, 0.05);
            border-radius: 6px;
            margin: 1px;
            transition: background-color 0.3s ease;
        }
        
        .fixtures-table tbody tr:hover td {
            background: rgba(255, 255, 255, 0.15);
        }
        
        .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>
    <div class="overlay-container">
        <div class="fixtures-panel" id="fixturesPanel">
            <div class="fixtures-title">Today's matches</div>
            <div class="loading-message" id="loadingMessage" style="display: none;">Loading fixture data...</div>
            <div id="fixturesContent" style="display: none;">
                <table class="fixtures-table" id="fixturesTable">
                    <thead>
                        <tr id="tableHeader">
                            <th>Match</th>
                            <th>Fighters</th>
                            <th>Venue</th>
                            <th>WIN1</th>
                            <th>X</th>
                            <th>WIN2</th>
                            <th>UNDER</th>
                            <th>OVER</th>
                        </tr>
                    </thead>
                    <tbody id="tableBody">
                        <!-- Content will be populated by JavaScript -->
                    </tbody>
                </table>
            </div>
            <div class="no-matches" id="noMatches" style="display: none;">
                No matches available for today's fixture
            </div>
        </div>
    </div>

    <script>
        // Global variables for overlay data handling
        let overlayData = {};
        let fixturesData = null;
        let outcomesData = null;
        
        // Web server configuration - will be set via WebChannel
        let webServerBaseUrl = 'http://127.0.0.1:5001';  // Default fallback
        
        // Function to update overlay data (called by Qt WebChannel)
        function updateOverlayData(data) {
            console.log('Received overlay data:', data);
            overlayData = data || {};
            
            // Update web server base URL if provided
            if (data && data.webServerBaseUrl) {
                webServerBaseUrl = data.webServerBaseUrl;
                console.log('Updated web server base URL:', webServerBaseUrl);
            }
            
            // Check if we have fixtures data
            if (data && data.fixtures) {
                fixturesData = data.fixtures;
                renderFixtures();
            } else {
                // Fetch fixtures data from API
                fetchFixturesData();
            }
        }
        
        // Fetch fixtures data from the API
        async function fetchFixturesData() {
            try {
                console.log('Fetching fixtures data from API...');
                
                // Try multiple API endpoints with different authentication levels
                const apiEndpoints = [
                    `${webServerBaseUrl}/api/cashier/pending-matches`,
                    `${webServerBaseUrl}/api/fixtures`,
                    `${webServerBaseUrl}/api/status`  // Fallback to basic status endpoint
                ];
                
                let apiData = null;
                let usedEndpoint = null;
                
                for (const endpoint of apiEndpoints) {
                    try {
                        console.log(`Trying API endpoint: ${endpoint}`);
                        const response = await fetch(endpoint, {
                            method: 'GET',
                            headers: {
                                'Content-Type': 'application/json'
                            },
                            credentials: 'include'  // Include cookies for authentication
                        });
                        
                        if (response.ok) {
                            const data = await response.json();
                            console.log(`API Response from ${endpoint}:`, data);
                            
                            if (data.success) {
                                apiData = data;
                                usedEndpoint = endpoint;
                                break;
                            }
                        } else {
                            console.warn(`API endpoint ${endpoint} returned status ${response.status}`);
                        }
                    } catch (endpointError) {
                        console.warn(`Failed to fetch from ${endpoint}:`, endpointError);
                        continue;
                    }
                }
                
                if (apiData && apiData.matches && apiData.matches.length > 0) {
                    console.log(`Found ${apiData.matches.length} matches from ${usedEndpoint}`);
                    fixturesData = apiData.matches;
                    renderFixtures();
                    return Promise.resolve();
                } else if (apiData && apiData.fixtures && apiData.fixtures.length > 0) {
                    // Handle fixtures endpoint format
                    console.log(`Found ${apiData.fixtures.length} fixtures from ${usedEndpoint}`);
                    // Convert fixtures to matches format
                    fixturesData = [];
                    apiData.fixtures.forEach(fixture => {
                        if (fixture.matches) {
                            fixturesData.push(...fixture.matches);
                        }
                    });
                    if (fixturesData.length > 0) {
                        renderFixtures();
                        return Promise.resolve();
                    }
                }
                
                // If we reach here, no valid data was found
                console.log('No fixture data available from any API endpoint, will show fallback');
                return Promise.reject('No API data available');
            } catch (error) {
                console.error('Error fetching fixtures data:', error);
                return Promise.reject(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 }
            ];
        }
        
        // Render the fixtures table
        function renderFixtures() {
            const loadingMessage = document.getElementById('loadingMessage');
            const fixturesContent = document.getElementById('fixturesContent');
            const noMatches = document.getElementById('noMatches');
            const tableHeader = document.getElementById('tableHeader');
            const tableBody = document.getElementById('tableBody');
            
            loadingMessage.style.display = 'none';
            noMatches.style.display = 'none';
            
            if (!fixturesData || fixturesData.length === 0) {
                showNoMatches('No matches available for today');
                return;
            }
            
            // Get all available outcomes from the matches
            const allOutcomes = new Set();
            fixturesData.forEach(match => {
                if (match.outcomes && match.outcomes.length > 0) {
                    match.outcomes.forEach(outcome => {
                        // Handle both API formats
                        const outcomeName = outcome.outcome_name || outcome.column_name;
                        if (outcomeName) {
                            allOutcomes.add(outcomeName);
                            console.log(`Found outcome: ${outcomeName} for match ${match.id}`);
                        }
                    });
                }
            });
            
            console.log(`Total unique outcomes found: ${allOutcomes.size}`, Array.from(allOutcomes));
            
            // Sort outcomes: common ones first, then alphabetically
            const sortedOutcomes = Array.from(allOutcomes).sort((a, b) => {
                // Priority order for common outcomes
                const priority = {
                    'WIN1': 1, 'X': 2, 'WIN2': 3, 'DRAW': 4,
                    'UNDER': 5, 'OVER': 6, 'KO1': 7, 'KO2': 8,
                    'PTS1': 9, 'PTS2': 10, 'DKO': 11, 'RET1': 12, 'RET2': 13
                };
                
                const aPriority = priority[a] || 100;
                const bPriority = priority[b] || 100;
                
                if (aPriority !== bPriority) {
                    return aPriority - bPriority;
                }
                
                return a.localeCompare(b);
            });
            
            console.log('Sorted outcomes:', sortedOutcomes);
            
            // Create table header
            tableHeader.innerHTML = `
                <th>Match</th>
                <th>Fighters</th>
                <th>Venue</th>
                ${sortedOutcomes.map(outcome => `<th>${outcome}</th>`).join('')}
            `;
            
            // Create table body
            tableBody.innerHTML = '';
            
            fixturesData.forEach(match => {
                const row = document.createElement('tr');
                
                // Create outcomes map for quick lookup
                const outcomeMap = {};
                if (match.outcomes && match.outcomes.length > 0) {
                    match.outcomes.forEach(outcome => {
                        // Handle both API formats
                        const outcomeName = outcome.outcome_name || outcome.column_name;
                        const outcomeValue = outcome.outcome_value || outcome.float_value;
                        if (outcomeName) {
                            outcomeMap[outcomeName] = outcomeValue;
                        }
                    });
                }
                
                console.log(`Match ${match.id || match.match_number}: Found ${Object.keys(outcomeMap).length} outcomes`);
                
                row.innerHTML = `
                    <td class="match-info">#${match.match_number || match.id || 'N/A'}</td>
                    <td class="fighter-names">
                        ${match.fighter1_township || match.fighter1 || 'Fighter 1'}<br>vs<br>${match.fighter2_township || match.fighter2 || 'Fighter 2'}
                    </td>
                    <td class="venue-info">${match.venue_kampala_township || match.venue || 'TBD'}</td>
                    ${sortedOutcomes.map(outcome => {
                        const odds = outcomeMap[outcome];
                        const isUnderOver = outcome === 'UNDER' || outcome === 'OVER';
                        const oddsClass = isUnderOver ? 'odds-value under-over' : 'odds-value';
                        const displayValue = odds !== undefined && odds !== null ? parseFloat(odds).toFixed(2) : '-';
                        return `<td><span class="${oddsClass}">${displayValue}</span></td>`;
                    }).join('')}
                `;
                
                tableBody.appendChild(row);
            });
            
            fixturesContent.style.display = 'block';
        }
        
        // Show no matches message
        function showNoMatches(message) {
            document.getElementById('loadingMessage').style.display = 'none';
            document.getElementById('fixturesContent').style.display = 'none';
            const noMatches = document.getElementById('noMatches');
            noMatches.textContent = message;
            noMatches.style.display = 'block';
        }
        
        // Initialize when DOM is loaded
        document.addEventListener('DOMContentLoaded', function() {
            console.log('Fixtures overlay initialized - attempting to fetch real data');
            
            // Show loading message initially
            document.getElementById('fixturesContent').style.display = 'none';
            document.getElementById('noMatches').style.display = 'none';
            document.getElementById('loadingMessage').style.display = 'block';
            document.getElementById('loadingMessage').textContent = 'Loading live fixture data...';
            
            // Start fetching real data immediately
            fetchFixturesData().then(() => {
                // If API fails completely, show fallback data after a short delay
                setTimeout(() => {
                    if (!fixturesData || fixturesData.length === 0) {
                        console.log('No data loaded after API attempts, forcing fallback display');
                        showFallbackMatches();
                    }
                }, 2000);
            }).catch(() => {
                console.log('API fetch failed, showing fallback data');
                showFallbackMatches();
            });
            
            // Refresh data every 30 seconds
            setInterval(function() {
                console.log('Refreshing fixture data...');
                fetchFixturesData();
            }, 30000);
        });
        
        // Qt WebChannel initialization (when available)
        if (typeof QWebChannel !== 'undefined') {
            new QWebChannel(qt.webChannelTransport, function(channel) {
                console.log('WebChannel initialized for fixtures overlay');
                
                // Connect to overlay object if available
                if (channel.objects.overlay) {
                    channel.objects.overlay.dataChanged.connect(function(data) {
                        updateOverlayData(data);
                    });
                    
                    // Get initial data
                    if (channel.objects.overlay.getCurrentData) {
                        channel.objects.overlay.getCurrentData(function(data) {
                            updateOverlayData(data);
                        });
                    }
                }
            });
        }
    </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>