<?php
function bongdako_shortcode_ranking_board()
{
    $assets = plugin_dir_url(__FILE__) . '/';
    $font = get_option('typography_main_player_board', []);
    $ch = true == get_option( 'Checkbox_unindex_sp', true );
    ob_start();

    ?>
    <link href="<?= $assets ?>style.css?v=<?= ASSETS_VERSION ?>" rel="stylesheet">
    <style>
        #scrollIframe.wrap-iframe-player_board * {
            font-family: <?php echo $font['font-family'] ?? ""; ?> !important;
        }


        body #ranking_board.wrap-iframe-player_board .bxh-110.lrdiv .lrdiv-title {
            color: <?php echo get_option('text_heading_color_player_board'); ?> !important;
        }

        body #ranking_board.wrap-iframe-player_board .bxh-110 .player-st-content-item-title * {
            color: <?php echo get_option('text_heading_table_color_player_board'); ?> !important;
        }

        body #ranking_board.wrap-iframe-player_board .bxh-110 #players-list .bxh-110-content-name {
            color: <?php echo get_option('text_heading_team_color_player_board'); ?> !important;
        }

        body #ranking_board.wrap-iframe-player_board .bxh-110 #teams-list .bxh-110-content-name {
            color: <?php echo get_option('text_heading_player_color_player_board'); ?> !important;
        }

        body #ranking_board.wrap-iframe-player_board .bxh-110 #teams-list .player-st-content-item-score {
            color: <?php echo get_option('text_heading_score_team_color_player_board'); ?> !important;
        }

        body #ranking_board.wrap-iframe-player_board .bxh-110 #players-list .player-st-content-item-score {
            color: <?php echo get_option('text_heading_score_player_color_player_board'); ?> !important;
        }

        body #ranking_board.wrap-iframe-player_board .bxh-110 .player-st-content-item-no {
            color: <?php echo get_option('text_heading_no_color_player_board'); ?> !important;
        }

    </style>
    <div id="ranking_board" class="wrap-iframe-player_board">
        <div class="lrdiv bxh-110">
            <div class="lrdiv-title"><?php esc_html_e('BẢNG XẾP HẠNG', 'sport'); ?></div>
            <div class="bxh-110-content-fc">
                <div class="custom-select-02 button-df mw-100 sixmix position-relative">
                    <div id="selected-league" class="custom-select3 six-in-one-custom-select">
                        <?php esc_html_e('Ngoại hạng Anh', 'sport'); ?>
                    </div>
                    <div class="custom-options scroll-custom" id="league-options">
                    </div>
                </div>
                <div id="teams-table" class="loading" style="display:none;">
                    <div class="player-st-content">
                        <div class="player-st-content-item player-st-content-item-title">
                            <div class="player-st-content-item-no">#</div>
                            <div class="player-st-content-item-name"><?php esc_html_e('Tên đội', 'sport'); ?></div>
                            <div class="player-st-content-item-score"><?php esc_html_e('Điểm', 'sport'); ?></div>
                        </div>
                        <div id="teams-list" class="flixt"></div>
                    </div>
                </div>
            </div>

            <div class="player_st">
                <div class="lrdiv-title"><?php esc_html_e('THỐNG KÊ CẦU THỦ', 'sport'); ?></div>
                <div id="players-table" class="loading" style="display:none;">
                    <div class="player-st-content">
                        <div class="player-st-content-item player-st-content-item-title">
                            <div class="player-st-content-item-no">#</div>
                            <div class="player-st-content-item-name"><?php esc_html_e('Tên cầu thủ', 'sport'); ?></div>
                            <div class="player-st-content-item-score"><?php esc_html_e('Bàn thắng', 'sport'); ?></div>
                        </div>
                        <div id="players-list" class="flixt"></div>

                    </div>
                </div>
            </div>
        </div>
    </div>

    <script>
        document.addEventListener('click', function (event) {
            if (event.target.closest('.bxh-110 .custom-select3')) {
                document.querySelectorAll('.custom-options').forEach(option => {
                    option.classList.remove('show');
                });

                const parentSelect = event.target.closest('.custom-select-02');
                if (parentSelect) {
                    const optionsEl = parentSelect.querySelector('.custom-options');
                    if (optionsEl) {
                        optionsEl.classList.toggle('show');
                    }
                }
            } else {
                document.querySelectorAll('.custom-options').forEach(option => {
                    option.classList.remove('show');
                });
            }
        });


        const filter = {
            leagueId: {
                value: 36,
                label: ' <?php esc_html_e('Ngoại hạng Anh', 'sport') ?>',
                nameUrl: 'ngoai-hang-anh-36'
            }
        };


        const optionLeague = [
            // { value: 103, label: "Champions League", nameUrl: "uefa-champions-league-103" },
            {value: 36, label: '<?php esc_html_e('Ngoại hạng Anh', 'sport') ?>', nameUrl: "ngoai-hang-anh-36"},
            {value: 31, label: "<?php esc_html_e('VĐQG Tây Ban Nha', 'sport'); ?>", nameUrl: "vdqg-tay-ban-nha-31"},
            {value: 34, label: "<?php esc_html_e('VĐQG Ý', 'sport'); ?>", nameUrl: "vdqg-y-34"},
            {value: 8, label: "<?php esc_html_e('VĐQG Đức', 'sport'); ?>", nameUrl: "vdqg-duc-8"},
            {value: 11, label: "<?php esc_html_e('VĐQG Pháp', 'sport'); ?>", nameUrl: "vdqg-phap-11"},
            // { value: 113, label: "Europa League", nameUrl: "europa-league-113" },
            // { value: 67, label: "Euro 2024", nameUrl: "euro-2024-67" },
            // { value: 766, label: "VĐQG Việt Nam", nameUrl: "v-league-766" },
            {value: 37, label: "<?php esc_html_e('EFL Championship', 'sport'); ?>", nameUrl: "hang-nhat-anh-37"},
            {value: 23, label: "<?php esc_html_e('VĐQG Bồ Đào Nha', 'sport'); ?>", nameUrl: "vdqg-bo-dao-nha-23"},
            {value: 9, label: "<?php esc_html_e('Giải hạng 2 Đức', 'sport'); ?>", nameUrl: "hang-hai-duc-9"},
            // { value: 12, label: "Giải hạng 2 Pháp", nameUrl: "hang-hai-phap-12" }
        ];

        let teams = [];
        let players = [];
        let loading = false;
        let isFirstLoad = true;

        function handleChange(value) {
            const selectedItem = optionLeague.find(option => option.value === value);
            if (!selectedItem) {
                return;
            }
            filter.leagueId = selectedItem;
            document.getElementById("selected-league").textContent = selectedItem.label;
            fetchLeagueRank(selectedItem.value);
            document.querySelectorAll('.custom-options').forEach(option => {
                option.classList.remove('show');
            });
        }

        function fetchLeagueRank(value) {
            loading = true;
            toggleLoading();
            var dbUrl2 = "<?= DB_DOMAIN ?>";
            fetch(`${dbUrl2}/api/get-league-rank?sid=${value}`)
                .then(response => response.json())
                .then(data => {
                    teams = data.data_rank.slice(0, 10) || [];
                    players = data.data_player.slice(0, 10) || [];
                    updateUI();
                })
                .catch(error => console.error("Failed to fetch league rank data:", error))
                .finally(() => {
                    loading = false;
                    toggleLoading();
                });
        }

        function convertToSlug(text) {
            return text
                .toLowerCase()                      // Convert to lowercase
                .trim()                             // Remove leading and trailing whitespace
                .replace(/[\s_]+/g, '-')            // Replace spaces and underscores with a hyphen
                .replace(/[^\w\-]+/g, '')           // Remove all non-word characters
                .replace(/\-\-+/g, '-');            // Replace multiple hyphens with a single hyphen
        }

        function toggleLoading() {
            document.getElementById("teams-table").className = loading ? "loading" : "";
            document.getElementById("players-table").className = loading ? "loading" : "";
        }

        function updateUI() {
            const teamsList = document.getElementById("teams-list");
            teamsList.innerHTML = teams.map((team, index) => `
             <div class="player-st-content-item">
                            <div class="player-st-content-item-no">${index + 1}</div>
                            <div class="player-st-content-item-name"><a <?php echo  $ch ? 'rel="nofollow"':'' ?>  href="#" class="bxh-110-content-name" target="_blank">
                     ${team.Name_E}
                </a></div>
                            <div class="player-st-content-item-score">${team.Points}</div>
                        </div>
        `).join('');

            const playersList = document.getElementById("players-list");
            playersList.innerHTML = players.map((player, index) => `
            <div class="player-st-content-item">
                            <div class="player-st-content-item-no">${index + 1}</div>
                            <div class="player-st-content-item-name"><a  <?php echo  $ch ? 'rel="nofollow"':'' ?> href="#" class="bxh-110-content-name" target="_blank">
                    ${player.name}
                </a></div>
                            <div class="player-st-content-item-score">${player.score}</div>
                        </div>

        `).join('');

            if (isFirstLoad) {
                document.getElementById("teams-table").style.display = "block";
                document.getElementById("players-table").style.display = "block";
                isFirstLoad = false;
            }
        }


        const leagueOptions = document.getElementById("league-options");
        leagueOptions.innerHTML = optionLeague.map((item, index) => `
            <div onclick="handleChange(${JSON.stringify(item.value)})" class="custom-option">
                ${item.label}
            </div>
        `).join('');

        fetchLeagueRank(filter.leagueId.value);


    </script>
    <?php
    $content = ob_get_contents();
    ob_end_clean();
    return $content;
}

add_shortcode('bongdako_ranking_player_board', 'bongdako_shortcode_ranking_board');