<!DOCTYPE html>
{% load static %}
{% load qr_code %}
<html>
    <head>
        <meta http-equiv="content-type" content="text/html; charset=UTF-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />
        <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' %}" />
        <style>
            .bubble {
                padding: 10px;
                background-color: white;
                border-radius: 24px;
                box-shadow: 0 0 0px 0px #fbead6;
            }
            .running {
                background-color: #90ee90 !important;
            }
            .timeslot {
                font-family: "Anybody-ExtraBold";
                font-size: clamp(0.4rem, 1.5vw - 0.2rem, 3rem); /* Adjust these values as needed */
                color: white;
            }
            .match-cell {
                box-sizing: border-box;
                padding: 0;
                flex-grow: 0;
                flex-shrink: 0;
            }
            .match-cell .bubble {
                height: 13vh;
                display: flex;
                flex-direction: column;
                justify-content: center;
                box-sizing: border-box;
                /* Dynamic font size based on viewport width */
                font-size: clamp(0.6rem, 1.2vw - 0.2rem, 5rem); /* Adjust these values as needed */
                overflow: hidden;
                text-overflow: ellipsis;
                color: black;
                background-color: white;
                margin: 0;
                width: 100%;
            }
            .match-cell .bubble.even {
                background-color: white;
            }
            .match-cell .bubble.empty {
                background-color: rgba(173, 216, 230, 0.3);
                color: white;
            }
            .match-cell .bubble.ended {
                background-color: rgba(173, 216, 230, 0.3);
            }
            .court-label {
                box-sizing: border-box;
                padding: 0;
                flex-grow: 0;
                flex-shrink: 0;
            }
            .court-label .bubble {
                height: 4vh;
                font-weight: bold;
                margin: 0;
                width: 100%;
                text-align: center;
                display: flex;
                align-items: center;
                justify-content: center;
                /* Slightly smaller dynamic font size for court labels */
                font-size: clamp(0.7rem, 0.8vw + 0.1rem, 3rem); /* Adjust these values as needed */
                color: white;
                background: #1a223a;
            }
            .bubble-timeslot {
                color: white;
                background: #1a223a;
                display: flex;
                border-radius: 24px;
                box-shadow: 0 0 0px 0px #fbead6;
                align-items: center;
                justify-content: center;
                padding: 0px 20px;
                margin: 0;
            }
            .courts-row,
            .matches-row {
                display: flex;
                width: 100%;
                gap: 10px;
            }
            .grid-x {
                display: flex;
                flex-wrap: wrap;
            }
            .matchtitle {
                font-size: inherit; /* Inherit the dynamic font size from .bubble */
                font-weight: bold;
                margin-bottom: 0.2em;
                overflow: hidden;
                text-overflow: ellipsis;
                white-space: nowrap;
            }
            .minor-info {
                font-size: inherit; /* Inherit the dynamic font size from .bubble */
                font-weight: normal;
                overflow: hidden;
                text-overflow: ellipsis;
                white-space: nowrap;
            }
            .score {
                font-size: inherit; /* Inherit the dynamic font size from .bubble */
            }
            .bold {
                font-weight: bold;
            }
            .ws {
                white-space: nowrap;
            }
        </style>

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

        <title>Programmation</title>

        <script src="{% static 'tournaments/js/alpine.min.js' %}" defer></script>
        <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>
    </head>

    <body x-data="{
        days: [],
        currentDayIndex: 0,
        currentPageIndex: 0,
        has_sponsors: {{ tournament.has_sponsors|lower }},
        matchGroups: [],
        courtCount: {{ tournament.court_count|default:1 }},
        courtNames: {{ tournament.court_names }},
        retrieveData() {
            fetch('/tournament/{{ tournament.id }}/planning/json/')
                .then(res => res.json())
                .then((data) => {
                    this.days = data.days || [];
                    this.matchGroups = data.match_groups || [];
                    this.currentPageIndex = 0;

                    if (this.days.length > 0 && this.currentDayIndex >= this.days.length) {
                        this.currentDayIndex = 0;
                    }
                });
        },

        getMatchGroupsForDay(day) {
            let groupsPerPage = 12;
            if (window.innerHeight <=720) {
                groupsPerPage = 8;
            } else if (window.innerHeight <=1080) {
                groupsPerPage = 10;
            }

            if (this.has_sponsors) {
                groupsPerPage = groupsPerPage - 2;
            }

            const formattedDay = day;
            const filteredGroups = this.matchGroups.filter(group => {
                if (!group.matches || group.matches.length === 0) return false;
                return group.name && formattedDay && group.name.includes(formattedDay);
            });

            let groupsPerPageThreshold = this.courtCount >= 5 ? Math.ceil(groupsPerPage / 2) : groupsPerPage;
            let columns = this.courtCount >= 5 ? 1 : 2;  // Number of columns to display

            const paginatedGroups = [];
            for (let i = 0; i < Math.ceil(filteredGroups.length / groupsPerPageThreshold); i++) {
                // For each page
                const pageGroups = filteredGroups.slice(i * groupsPerPageThreshold, (i + 1) * groupsPerPageThreshold);

                // Rearrange groups in vertical order
                if (columns === 2) {

                    if (this.courtCount < 5 && pageGroups.length < groupsPerPageThreshold / 2) {
                        const pageLength = pageGroups.length;
                        const rearrangedGroups = new Array(pageGroups.length);
                        for (let col = 0; col < pageLength; col++) {
                            rearrangedGroups[col * 2] = pageGroups[col]; // First column: indices 0, 2, 4, etc.
                        }
                        paginatedGroups.push(rearrangedGroups);
                    } else {
                        const rearrangedGroups = [];
                        const halfPageLength = Math.ceil(pageGroups.length / 2);

                        // Create groups with alternating order: [0, halfPageLength, 1, halfPageLength+1, ...]
                        for (let col = 0; col < halfPageLength; col++) {
                            rearrangedGroups.push(pageGroups[col]); // First column
                            if (col + halfPageLength < pageGroups.length) {
                                rearrangedGroups.push(pageGroups[col + halfPageLength]); // Second column
                            }
                        }
                        paginatedGroups.push(rearrangedGroups);
                    }
                } else {
                    paginatedGroups.push(pageGroups);
                }
            }
            return paginatedGroups;
        },

        getCourtNumber(courtIndex) {
            if (courtIndex == null) return 999;
            return courtIndex;
        },

        organizeMatchesByCourt(group) {
            if (!group || !group.matches) {
                return Array(this.courtCount).fill(null);
            }
            const matches = group.matches;
            const courtMatches = Array(this.courtCount).fill(null);
            if (matches && matches.length > 0) {
                matches.forEach(match => {
                    if (match && match.court) {
                        const courtNum = this.getCourtNumber(match.court_index);
                        if (courtNum >= 0 && courtNum < this.courtCount) {
                            courtMatches[courtNum] = match;
                        }
                    }
                });
            }
            return courtMatches;
        },

        loop() {
            this.retrieveData();
            setInterval(() => {
                if (this.days.length > 0) {
                    const currentDay = this.days[this.currentDayIndex];
                    const pagesForDay = this.getMatchGroupsForDay(currentDay);

                    if (pagesForDay && pagesForDay.length > 1) {
                        const _currentPageIndex = this.currentPageIndex;
                        this.currentPageIndex = (this.currentPageIndex + 1) % pagesForDay.length;
                        if (_currentPageIndex >= 1 && this.currentPageIndex === 0) {
                            this.currentDayIndex = (this.currentDayIndex + 1) % this.days.length;
                        }
                    } else {
                        this.currentPageIndex = 0;
                        this.currentDayIndex = (this.currentDayIndex + 1) % this.days.length;
                    }
                } else {
                    this.currentDayIndex = 0;
                    this.currentPageIndex = 0;
                }
            }, 20000);
        },

        calculateFractionWidth() {
            if (this.courtCount >= 5) {
                const reductionFactor = 0.94; // Adjust this value
                return `calc((100% / ${this.courtCount}) * ${reductionFactor})`;
            } else {
                const reductionFactor = 0.90; // Adjust this value
                return `calc((100% / (${this.courtCount})) * ${reductionFactor})`;
            }
        }
    }" x-init="loop()">

        <header>
            <div id="header" class="header-broadcast">
                <div class="left-content bubble-header">
                    <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" x-text="days[currentDayIndex]"></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="grid-x">
                    <div class="cell" :class="{'large-12': courtCount >= 5, 'large-6': courtCount < 5}">
                        <div style="display: flex; margin-bottom: 10px;">
                            <div class="bubble-timeslot" style="visibility: hidden; align-items: center; justify-content: center; margin-right: 10px; width: 6vw;">
                                <h1 class="timeslot">00:00</h1>
                            </div>
                            <div class="courts-row" style="margin-left: 10px; margin-bottom: -10px;">
                                <template x-for="courtName in courtNames" :key="courtName">
                                    <div class="court-label" :style="{'width': calculateFractionWidth()}">
                                        <div class="bubble">
                                            <div class="score ws bold"><span x-text="courtName"></span></div>
                                        </div>
                                    </div>
                                </template>
                            </div>
                        </div>
                    </div>
                    <div class="cell" :class="{'large-12': courtCount >= 5, 'large-6': courtCount < 5}" x-show="courtCount < 5">
                        <div style="display: flex; margin-bottom: 10px;">
                            <div class="bubble-timeslot" style="visibility: hidden; align-items: center; justify-content: center; margin-right: 10px; width: 6vw;">
                                <h1 class="timeslot">00:00</h1>
                            </div>
                            <div class="courts-row" style="margin-bottom: -10px;">
                                <template x-for="courtName in courtNames" :key="courtName">
                                    <div class="court-label" :style="{'width': calculateFractionWidth()}">
                                        <div class="bubble">
                                            <div class="score ws bold"><span x-text="courtName"></span></div>
                                        </div>
                                    </div>
                                </template>
                            </div>
                        </div>
                    </div>
                </div>

                <template x-for="(day, dayIndex) in days" :key="day">
                    <div class="padding10" x-show="currentDayIndex === dayIndex">
                        <template x-for="(groupPage, pageIndex) in getMatchGroupsForDay(day)" :key="'page-' + pageIndex">
                            <div x-show="currentPageIndex === pageIndex">
                                <div class="grid-x">
                                    <template x-for="(group, groupIndex) in groupPage" :key="groupIndex">
                                        <div class="cell" :class="{'large-12': courtCount >= 5, 'large-6': courtCount < 5}">
                                            <div style="display: flex; margin-bottom: 10px;">
                                                <div class="bubble-timeslot" style="align-items: center; justify-content: center; margin-right: 10px; width: 6vw;">
                                                    <h1 class="timeslot" x-text="group && group.name ? group.name.slice(-5) : ''"></h1>
                                                </div>

                                                <div class="matches-row">
                                                    <template x-for="(match, courtIndex) in organizeMatchesByCourt(group)" :key="courtIndex">
                                                        <div class="match-cell" :style="{'width': calculateFractionWidth()}">
                                                            <template x-if="match">
                                                                <div class="bubble" :class="{'running': !match.ended && match.started, 'even': courtIndex % 2 === 1, 'ended': match.ended}" style="text-align: center;">
                                                                    <template x-if="match.tournament_title">
                                                                        <div class="minor-info semibold" x-text="match.tournament_title"></div>
                                                                    </template>
                                                                    <div class="bold" x-text="match.group_stage_name ? match.group_stage_name : match.title"></div>
                                                                    <div class="minor-info" x-text="match.format"></div>
                                                                </div>
                                                            </template>
                                                            <template x-if="!match">
                                                                <div class="bubble empty" style="text-align: center;">
                                                                </div>
                                                            </template>
                                                        </div>
                                                    </template>
                                                </div>
                                            </div>
                                        </div>
                                    </template>
                                </div>
                            </div>
                        </template>
                    </div>
                </template>
            </main>
        </div>

        <footer class="footer-broadcast">
            {% if tournament.event.images.exists %}
            <div class="bubble-footer">
                <div class="bubble-sponsor">
                    {% for image in tournament.event.images.all %}
                        <img src="{{ image.image.url }}" alt="{{ image.title|default:'Sponsor' }}"
                             class="sponsor-logo-broadcast">
                    {% endfor %}
                </div>
            </div>
            {% endif %}
        </footer>
    </body>
</html>
