<!DOCTYPE html>
<html>
    <head>
        <title>Club 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;
            }
        </style>
    </head>

    <body>
        <iframe id="tournamentFrame" src="about:blank"></iframe>

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

            function loadNextTournament() {
                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 pour {{ club_name }}</div>';
                    return;
                }

                const tournamentId = tournamentIds[currentIndex];
                const url = `/tournament/${tournamentId}/broadcast/auto/`;

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

                frame.src = url;
                currentIndex = (currentIndex + 1) % tournamentIds.length;
            }

            // 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, 1000); // Switch after 1 second
                } else if (event.data.type === 'tournamentError') {
                    console.error(`Tournament ${event.data.tournamentId.substring(0, 8)} failed: ${event.data.error}`);
                    console.log('Switching to next tournament due to error...');
                    setTimeout(loadNextTournament, 2000); // Switch after 2 seconds on error
                }
            });

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