<!DOCTYPE html>
{% load static %}
{% load qr_code %}
<html>
<head>
    <meta http-equiv="content-type" content="text/html; charset=UTF-8" />
    <link rel="stylesheet" href="{% static 'tournaments/css/foundation.min.css' %}" />
    <link rel="stylesheet" href="{% static 'tournaments/css/basics.css' %}" />
    <link rel="stylesheet" href="{% static 'tournaments/css/style.css' %}" />
    <link rel="stylesheet" href="{% static 'tournaments/css/broadcast.css' %}" />
    <link rel="stylesheet" href="{% static 'tournaments/css/tournament_bracket.css' %}" />

    <link rel="icon" type="image/png" href="{% static 'tournaments/images/favicon.png' %}" />

    <title>Tableau</title>

    <script src="{% static 'tournaments/js/alpine.min.js' %}"></script>
    <!-- Matomo -->
    <script>
      var _paq = window._paq = window._paq || [];
      /* tracker methods like "setCustomDimension" should be called before "trackPageView" */
      _paq.push(["setDocumentTitle", document.domain + "/" + document.title]);
      _paq.push(["setDoNotTrack", true]);
      _paq.push(['trackPageView']);
      _paq.push(['enableLinkTracking']);
      (function() {
        var u="//matomo.padelclub.app/";
        _paq.push(['setTrackerUrl', u+'matomo.php']);
        _paq.push(['setSiteId', '1']);
        var d=document, g=d.createElement('script'), s=d.getElementsByTagName('script')[0];
        g.async=true; g.src=u+'matomo.js'; s.parentNode.insertBefore(g,s);
      })();
    </script>
    <!-- End Matomo Code -->
</head>

<body>
    <header>
        <div id="header">
            <div class="left-content bubble">
                <img src="{% static 'tournaments/images/PadelClub_logo_512.png' %}" alt="logo" class="logo">
                <div class="left-margin">
                    <h1 class="club">{{ tournament.broadcast_event_display_name }}</h1>
                    <h1 class="event">Tableau {{ tournament.broadcast_display_name }}</h1>
                </div>
            </div>
            <div class="right-content">{% qr_from_text qr_code_url options=qr_code_options %}</div>
        </div>
    </header>

    <div class="wrapper">
        <main>
            <div class="bracket-container">
                <div class="butterfly-bracket" id="bracket"></div>
            </div>
        </main>
    </div>

    <script src="{% static 'tournaments/js/tournament_bracket.js' %}"></script>
    <script>
        // Simple vanilla JS to handle the bracket rendering
        const tournamentId = "{{ tournament.id }}";

        function createMatchHTML(match) {
            let html = '<div>';

            // Generate HTML for each team
            match.teams.forEach((team, teamIndex) => {
                html += `
                    <div class="match-result ${teamIndex === 0 ? 'bottom-border' : ''}">
                        <div class="player ${team.names.length === 1 ? 'single-player' : 'two-players'}">
                            ${team.is_lucky_loser ? '<div class="overlay-text">(LL)</div>' : ''}
                            ${team.walk_out === 1 ? '<div class="overlay-text">(WO)</div>' : ''}

                            ${team.names.map(name => `
                                <div class="semibold ${team.walk_out === 1 ? 'strikethrough' : ''} ${team.is_winner ? 'winner' : ''}">
                                    ${name && name.length > 0 ? name : '&nbsp;'}
                                </div>
                            `).join('')}
                        </div>

                        ${match.has_walk_out ? `
                            <span class="score ws w60px">${team.is_walk_out ? 'WO' : ''}</span>
                        ` : ''}

                        ${team.scores && team.scores.length > 0 ? `
                            <div class="scores">
                                ${team.scores.map(score => `
                                    <span class="score ws ${score.tiebreak ? 'w35px' : 'w30px'} ${team.is_winner ? 'winner' : ''}">
                                        ${score.main}
                                        ${score.tiebreak ? `<sup>${score.tiebreak}</sup>` : ''}
                                    </span>
                                `).join('')}
                            </div>
                        ` : ''}

                        ${team.weight && !match.has_walk_out && (!team.scores || team.scores.length === 0) ? `
                            <span class="score ws numbers">${team.weight}</span>
                        ` : ''}
                    </div>
                `;
            });
            html += '</div>';
            return html;
        }

        function fetchAndRenderBracket() {
            fetch('/tournament/' + tournamentId + '/bracket/json/')
                .then(res => res.json())
                .then((data) => {
                    // Create a hidden div to hold all our match templates
                    const tempContainer = document.createElement('div');
                    tempContainer.style.display = 'none';
                    tempContainer.id = 'match-templates';
                    document.body.appendChild(tempContainer);

                    // Create templates for each match with the right data attributes
                    data.match_groups.forEach((group, groupIndex) => {
                        group.matches.forEach((match, matchIndex) => {
                            const template = document.createElement('div');
                            template.className = 'match-template';
                            template.dataset.matchRound = groupIndex;
                            template.dataset.matchIndex = matchIndex;
                            template.dataset.disabled = match.disabled;
                            template.dataset.matchGroupName = group.name;
                            template.dataset.matchFormat = match.format;
                            template.dataset.matchTitle = match.title;
                            template.dataset.roundId = group.round_id;
                            template.dataset.matchRealIndex = match.index;

                            // Create the match content using our HTML generator
                            template.innerHTML = `<div class="bubble broadcast-bracket-match ${(!match.ended && match.started) ? 'match-running' : ''}">${createMatchHTML(match)}</div>`;

                            tempContainer.appendChild(template);
                        });
                    });

                    // Now call the renderBracket function with our data
                    renderBracket({
                        doubleButterflyMode: true,
                        displayLoserFinal: true,
                        tournamentId: tournamentId,
                        isBroadcast: true
                    });

                    // Clean up our temporary container
                    document.body.removeChild(tempContainer);

                    document.getElementById('bracket').classList.add('broadcast-mode');

                });
        }

        // Initial render
        fetchAndRenderBracket();

        // Set up the refresh interval
        setInterval(fetchAndRenderBracket, 15000);
    </script>
</body>
</html>
