<!DOCTYPE html>
<html>
    <head>
        <title>Event Auto Broadcast</title>
        <style>
            * {
                margin: 0;
                padding: 0;
                box-sizing: border-box;
            }

            html, body {
                height: 100%;
                overflow: hidden;
                background-color: #000;
            }

            iframe {
                width: 100vw;
                height: 100vh;
                border: none;
                display: block;
                background-color: #000;
            }

            .error-message {
                position: absolute;
                top: 50%;
                left: 50%;
                transform: translate(-50%, -50%);
                color: white;
                font-size: 18px;
                text-align: center;
                z-index: 1000;
                display: none;
            }
        </style>
    </head>

    <body>
        <div class="error-message" id="errorMessage">
            Rechargement du tournoi...
        </div>
        <iframe id="tournamentFrame" src="about:blank"></iframe>

        <script>
            const tournamentIds = {{ tournament_ids|safe }};
            let currentIndex = 0;
            const frame = document.getElementById('tournamentFrame');
            const errorMessage = document.getElementById('errorMessage');
            let retryCount = 0;
            const maxRetries = 2;

            function loadNextTournament(isRetry = false) {
                if (tournamentIds.length === 0) {
                    document.body.innerHTML = '<div style="display: flex; align-items: center; justify-content: center; height: 100vh; font-size: 24px; color: white;">Aucun tournoi disponible</div>';
                    return;
                }

                if (!isRetry) {
                    retryCount = 0;
                    // Move to next tournament only if not retrying
                    currentIndex = (currentIndex + 1) % tournamentIds.length;
                }

                // Hide error message when loading new tournament
                errorMessage.style.display = 'none';

                const tournamentId = tournamentIds[currentIndex === 0 ? tournamentIds.length - 1 : currentIndex - 1];
                const url = `/tournament/${tournamentId}/broadcast/auto/`;

                console.log(`${isRetry ? 'Retrying' : 'Loading'} tournament ${currentIndex}/${tournamentIds.length}: ${tournamentId.substring(0, 8)} (attempt ${retryCount + 1})`);

                frame.src = url;

                // Set a timeout to detect if iframe fails to load
                const loadTimeout = setTimeout(() => {
                    console.warn(`Tournament ${tournamentId.substring(0, 8)} failed to load (attempt ${retryCount + 1})`);
                    handleLoadFailure();
                }, 8000); // 8 second timeout

                // Clear timeout when iframe loads successfully
                frame.onload = function() {
                    clearTimeout(loadTimeout);
                    retryCount = 0; // Reset retry count on successful load
                    console.log(`Tournament ${tournamentId.substring(0, 8)} loaded successfully`);
                };

                frame.onerror = function() {
                    clearTimeout(loadTimeout);
                    console.error(`Tournament ${tournamentId.substring(0, 8)} failed to load with error`);
                    handleLoadFailure();
                };
            }

            function handleLoadFailure() {
                if (retryCount < maxRetries) {
                    retryCount++;
                    errorMessage.textContent = `Rechargement du tournoi... (tentative ${retryCount + 1})`;
                    errorMessage.style.display = 'block';

                    console.log(`Retrying in 2 seconds... (attempt ${retryCount + 1}/${maxRetries + 1})`);
                    setTimeout(() => {
                        loadNextTournament(true); // Retry same tournament
                    }, 2000);
                } else {
                    // Max retries reached, move to next tournament
                    console.error('Max retries reached, moving to next tournament');
                    errorMessage.textContent = 'Tournoi indisponible, passage au suivant...';
                    errorMessage.style.display = 'block';

                    setTimeout(() => {
                        loadNextTournament(false); // Move to next tournament
                    }, 2000);
                }
            }

            // Listen for cycle completion messages from tournament iframe
            window.addEventListener('message', function(event) {
                if (event.data.type === 'tournamentCycleComplete') {
                    console.log(`Tournament completed (${event.data.reason})`);
                    setTimeout(() => loadNextTournament(false), 1000); // Switch after 1 second
                } else if (event.data.type === 'tournamentError') {
                    console.error(`Tournament ${event.data.tournamentId.substring(0, 8)} reported error: ${event.data.error}`);
                    handleLoadFailure(); // Treat as load failure
                }
            });

            // Load first tournament immediately
            loadNextTournament(false);
        </script>
    </body>
</html>
