document.addEventListener('DOMContentLoaded', function () {
    if (Object.keys(script).length !== 0) {
        const tabButtons = document.querySelectorAll('.catalog-bonus-tab button');

        if (tabButtons.length > 0) {
            const loadMoreButtons = document.querySelectorAll('.btn__load-more');
            const posts_per_page = document.querySelector('.bonus-tab-content').getAttribute('data-posts-per-page') ?? 40;

            // Load tabs
            tabButtons.forEach(function (button) {
                button.addEventListener('click', function (event) {
                    event.preventDefault();

                    let tabId = this.getAttribute('data-bs-target');
                    let tabPane = document.querySelector(tabId);
                    let tabPaneContent = tabPane.querySelector('.tab-content');

                    if (!tabPane.classList.contains('loaded')) {
                        let bonusData = Array.from(tabPane.querySelectorAll('.bonus-wrap')).map(function (bonusWrap) {

                            return {
                                'id': bonusWrap.getAttribute('data-id'),
                                'amount': JSON.parse(bonusWrap.getAttribute('data-amount')),
                                'description': bonusWrap.getAttribute('data-description'),
                                'casino': {
                                    'id': bonusWrap.getAttribute('data-casino-id'),
                                    'title': bonusWrap.getAttribute('data-casino-title'),
                                    'link': bonusWrap.getAttribute('data-casino-link'),
                                    'image': bonusWrap.getAttribute('data-casino-image'),
                                    'rating': bonusWrap.getAttribute('data-casino-rating'),
                                    'label': JSON.parse(bonusWrap.getAttribute('data-casino-label')),
                                    'label_custom_text': bonusWrap.getAttribute('data-casino-label-custom-text'),
                                    'label_custom_bg': bonusWrap.getAttribute('data-casino-label-custom-bg'),
                                    'ad': bonusWrap.getAttribute('data-casino-ad'),
                                    'terms': bonusWrap.getAttribute('data-casino-terms'),
                                    'disclaimer': bonusWrap.getAttribute('data-casino-disclaimer'),
                                    'deposit-methods': JSON.parse(bonusWrap.getAttribute('data-casino-deposit-methods')),
                                    'keitaro_api_link': bonusWrap.getAttribute('data-casino-keitaro-api-link')
                                }
                            };
                        });

                        let bonusDataJson = encodeURIComponent(JSON.stringify(bonusData));

                        tabPane.classList.add('loading');

                        let xhr = new XMLHttpRequest();
                        xhr.open('POST', script.ajaxurl, true);
                        xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
                        xhr.onreadystatechange = function () {
                            if (xhr.readyState === 4 && xhr.status === 200) {
                                tabPaneContent.innerHTML = xhr.responseText;

                                tabPane.classList.add('loaded');
                                tabPane.classList.remove('loading');
                            }
                        };

                        xhr.onerror = function () {
                            tabPane.innerHTML = script.errorLoadingText;
                        };

                        xhr.send('action=load_bonus_content&bonus_data=' + bonusDataJson + '&posts_per_page=' + posts_per_page);
                    }
                });
            });

            // Load more button
            if (loadMoreButtons) {
                loadMoreButtons.forEach(function (button) {
                    button.addEventListener('click', function (event) {
                        event.preventDefault();

                        let tabId = this.getAttribute('data-tab');
                        let tabPane = document.getElementById(tabId);
                        let tabPaneContent = tabPane.querySelector('.tab-content');

                        let excludeBonusIds = Array.from(tabPane.querySelectorAll('.bonus-wrap.not-loaded')).map(function (bonusWrap) {
                            return parseInt(bonusWrap.getAttribute('data-id'));
                        });

                        let bonusIds = JSON.parse(document.querySelector('.tab-pane.active').getAttribute('data-ids'));

                        let bonusData = Array.from(tabPane.querySelectorAll('.bonus-wrap.not-loaded')).map(function (bonusWrap) {
                            return {
                                'id': bonusWrap.getAttribute('data-id'),
                                'amount': JSON.parse(bonusWrap.getAttribute('data-amount')),
                                'description': bonusWrap.getAttribute('data-description'),
                                'casino': {
                                    'id': bonusWrap.getAttribute('data-casino-id'),
                                    'title': bonusWrap.getAttribute('data-casino-title'),
                                    'link': bonusWrap.getAttribute('data-casino-link'),
                                    'image': bonusWrap.getAttribute('data-casino-image'),
                                    'rating': bonusWrap.getAttribute('data-casino-rating'),
                                    'label': JSON.parse(bonusWrap.getAttribute('data-casino-label')),
                                    'label_custom_text': bonusWrap.getAttribute('data-casino-label-custom-text'),
                                    'label_custom_bg': bonusWrap.getAttribute('data-casino-label-custom-bg'),
                                    'ad': bonusWrap.getAttribute('data-casino-ad'),
                                    'terms': bonusWrap.getAttribute('data-casino-terms'),
                                    'disclaimer': bonusWrap.getAttribute('data-casino-disclaimer'),
                                    'deposit-methods': JSON.parse(bonusWrap.getAttribute('data-casino-deposit-methods')),
                                    'keitaro_api_link': bonusWrap.getAttribute('data-casino-keitaro-api-link')
                                }
                            };
                        });

                        let bonusDataJson = encodeURIComponent(JSON.stringify(bonusData));

                        tabPane.classList.add('loading');

                        let xhr = new XMLHttpRequest();
                        xhr.open('POST', script.ajaxurl, true);
                        xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');

                        xhr.onreadystatechange = function () {
                            if (xhr.readyState === 4 && xhr.status === 200) {
                                tabPaneContent.innerHTML += xhr.responseText;

                                tabPane.classList.remove('loading');
                                tabPane.classList.add('loaded-more');
                                button.remove()
                            }
                        };

                        xhr.onerror = function () {
                            console.error('Request failed');
                        };

                        xhr.send('action=load_more_bonuses&bonus_data=' + bonusDataJson + '&include_bonus_ids=' + bonusIds + '&exclude_bonus_ids=' + excludeBonusIds);
                    });
                });
            }
        }
    }
});
document.addEventListener('DOMContentLoaded', function () {
    if (Object.keys(script).length !== 0) {
        const form = document.querySelector('.comment-add-field__form');

        if (form) {
            form.addEventListener('submit', function (event) {
                event.preventDefault();

                let formFields = form.querySelectorAll('input, textarea');
                let allFieldsFilled = true;

                formFields.forEach(function (field) {
                    if (field.value.trim() === '') {
                        allFieldsFilled = false;
                        return;
                    }
                });

                let resultElement = document.querySelector('.comment-add-form__alert');

                resultElement.className = '';
                resultElement.textContent = '';

                if (allFieldsFilled) {
                    resultElement.classList.add('comment-add-form__alert', 'success');
                    resultElement.textContent = script.commentSuccess;

                    document.querySelectorAll('.star-form .star-rating .star').forEach(star => {
                        star.classList.remove('active');
                    });

                    form.reset();

                    setTimeout(function () {
                        resultElement.innerHTML = '';
                    }, 3000)
                } else {
                    resultElement.classList.add('comment-add-form__alert', 'error');
                    resultElement.textContent = script.commentError;
                }
            });
        }
    }
});

document.addEventListener('DOMContentLoaded', function () {
        const fullWidthColumns = document.querySelectorAll('.full-width');

        function updateFullWidthColumnStyles() {
            fullWidthColumns.forEach(function (fullWidthColumn) {
                const firstColumn = fullWidthColumn.querySelector('.wp-block-column:first-child');

                if (!fullWidthColumn.querySelector('.full-background')) {
                    firstColumn.innerHTML += '<div class="full-background"></div>';
                }

                const fullBg = fullWidthColumn.querySelector('.full-background');
                const fullWidthColumnHeight = fullWidthColumn.offsetHeight;
                const fullWidthColumnBg = window.getComputedStyle(fullWidthColumn).backgroundColor;

                fullBg.style.height = fullWidthColumnHeight + 'px';
                fullBg.style.marginTop = -fullWidthColumnHeight + 'px';
                fullBg.style.backgroundColor = fullWidthColumnBg;
            });
        }

        updateFullWidthColumnStyles();
        window.addEventListener('resize', updateFullWidthColumnStyles);
    }
)
document.addEventListener('DOMContentLoaded', function () {
    if (Object.keys(script).length !== 0) {

        const moreVendors = document.querySelector('#moreVendors');

        if (moreVendors) {
            const moreVendorsContainer = document.querySelector('.more-vendors');
            const vendorsGroup = document.querySelector('.vendors-group');
            const initialSlotOrder = Array.from(document.querySelectorAll('.slot'));


            // Toggle selects
            document.querySelectorAll('.select').forEach(function (select) {
                select.addEventListener('click', function (event) {
                    event.stopPropagation();

                    const selectBody = this.querySelector('.select-body');
                    if (selectBody.classList.contains('d-none')) {
                        selectBody.classList.remove('d-none');
                    } else {
                        selectBody.classList.add('d-none');
                    }
                });
            });

            document.addEventListener('click', function (event) {
                let targetElement = event.target;
                let selectBody = document.querySelector('.select-body');

                if (selectBody && !selectBody.contains(targetElement)) {
                    selectBody.classList.add('d-none');
                }
            });


            // Sort slots
            document.querySelectorAll('.value').forEach(function (value) {
                value.addEventListener('click', function () {
                    const isActive = this.classList.contains('active');

                    if (!isActive) {
                        document.querySelectorAll('.value').forEach(function (otherValue) {
                            otherValue.classList.remove('active');
                        });

                        this.classList.add('active');

                        const parentSelect = this.closest('.select');
                        if (parentSelect) {
                            const selectedElement = parentSelect.querySelector('.select-input .selected');
                            if (selectedElement) {
                                selectedElement.innerHTML = this.innerHTML;
                            }
                        }

                        const sortValue = this.getAttribute('data-value');
                        const slotsGroup = document.querySelector('.slots-group');
                        const slotArray = Array.from(slotsGroup.querySelectorAll('.slot'));

                        if (slotsGroup) {
                            if (sortValue === 'value-a-to-z') {
                                slotArray.sort(function (a, b) {
                                    const nameA = a.getAttribute('data-name').toUpperCase();
                                    const nameB = b.getAttribute('data-name').toUpperCase();
                                    if (nameA < nameB) {
                                        return -1;
                                    }
                                    if (nameA > nameB) {
                                        return 1;
                                    }
                                    return 0;
                                });
                            }

                            if (sortValue === 'value-new-to-old') {
                                slotArray.sort(function (a, b) {
                                    const dateA = getDateFromString(a.getAttribute('data-date'));
                                    const dateB = getDateFromString(b.getAttribute('data-date'));
                                    return dateB - dateA;
                                });
                            }

                            if (sortValue === 'value-rating') {
                                slotArray.sort(function (a, b) {
                                    const ratingA = parseFloat(a.getAttribute('data-rating'));
                                    const ratingB = parseFloat(b.getAttribute('data-rating'));
                                    return ratingB - ratingA;
                                });
                            }

                            slotsGroup.innerHTML = '';
                            slotArray.forEach(function (slot) {
                                slotsGroup.appendChild(slot);
                            });

                            if (sortValue === 'value-default') {
                                slotsGroup.innerHTML = '';
                                initialSlotOrder.forEach(function (slot) {
                                    slotsGroup.appendChild(slot);
                                });
                            }
                        }
                    }
                });
            });

            // Get date from string
            function getDateFromString(dateString) {
                const [day, month, year, hours, minutes, seconds] = dateString.split(/[\s.:]/);
                return new Date(year, month - 1, day, hours, minutes, seconds);
            }

            // Function for closing all providers
            function closeAllVendors(moreVendors, moreVendorsContainer, vendorsGroup) {
                moreVendors.querySelector('span').innerHTML = script.moreText;
                moreVendors.classList.remove('active')

                vendorsGroup.querySelectorAll('.vendor-item').forEach(function (item) {
                    item.innerHTML = '';
                });

                moreVendorsContainer.classList.add('d-none');
                moreVendorsContainer.classList.remove('loaded');
            }

            // Load vendors
            moreVendors.addEventListener('click', function () {
                if (moreVendors && !moreVendorsContainer.classList.contains('loaded')) {
                    moreVendors.querySelector('span').innerHTML = script.lessText;
                    moreVendors.classList.add('active')
                    moreVendorsContainer.classList.add('loaded')
                    moreVendorsContainer.classList.remove('d-none');
                    vendorsGroup.classList.add('loading');

                    let loaderElement = document.createElement('div');
                    loaderElement.classList.add('loader');
                    vendorsGroup.insertBefore(loaderElement, vendorsGroup.firstChild);

                    let allVendors = [];
                    document.querySelectorAll('.vendor-item').forEach(function (item) {
                        let vendorData = {
                            id: item.getAttribute('data-id'),
                            name: item.getAttribute('data-name'),
                            image: item.getAttribute('data-image')
                        };
                        allVendors.push(vendorData);
                    });

                    let xhr = new XMLHttpRequest();
                    xhr.open('POST', script.ajaxurl, true);
                    xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
                    xhr.onreadystatechange = function () {
                        if (xhr.readyState === 4 && xhr.status === 200) {
                            vendorsGroup.innerHTML = xhr.responseText;
                            loaderElement.remove()
                            vendorsGroup.classList.remove('loading');
                            // Remove previous event listener for .provider elements
                            document.querySelectorAll('.provider').forEach(function (vendor) {
                                vendor.removeEventListener('click', providerClickHandler);
                            });
                            // Reattach the event listener for the .provider elements
                            attachProviderClickEvent();
                        }
                    };

                    xhr.onerror = function () {
                        vendorsGroup.innerHTML = script.errorLoadingText;
                    };

                    xhr.send('action=load_all_vendors&all_vendors=' + JSON.stringify(allVendors));
                } else {
                    closeAllVendors(moreVendors, moreVendorsContainer, vendorsGroup)
                }

                document.querySelector('.select-body').classList.add('d-none')
            });

            // Function to handle click on .provider elements
            function providerClickHandler(event) {
                event.preventDefault();

                const vendorName = this.getAttribute('data-name');

                document.querySelectorAll('.provider').forEach(function (otherVendor) {
                    if (otherVendor !== this) {
                        otherVendor.classList.remove('active');
                    }
                }, this);

                const isActive = this.classList.contains('active');

                document.querySelectorAll('.provider').forEach(function (otherVendor) {
                    otherVendor.classList.remove('active');
                });

                if (!isActive) {
                    this.classList.add('active');
                }

                if (isActive) {
                    document.querySelectorAll('.slot').forEach(function (slot) {
                        slot.classList.remove('d-none');
                    });
                } else {
                    document.querySelectorAll('.slot').forEach(function (slot) {
                        const slotVendorName = slot.getAttribute('data-vendor-name');
                        if (vendorName !== slotVendorName) {
                            slot.classList.add('d-none');
                        } else {
                            slot.classList.remove('d-none');
                        }
                    });
                }

                document.querySelector('.select-body').classList.add('d-none')
                closeAllVendors(moreVendors, moreVendorsContainer, vendorsGroup);
            }

            // Function to attach event listener for the .provider elements
            function attachProviderClickEvent() {
                document.querySelectorAll('.provider').forEach(function (vendor) {
                    vendor.addEventListener('click', providerClickHandler);
                });
            }

            // Attach event listener for the .provider elements after DOMContentLoaded
            attachProviderClickEvent();

            // Reset all filters
            document.querySelector('.clear-filters').addEventListener('click', function () {
                const slotsGroup = document.querySelector('.slots-group');
                const defaultValueElement = document.querySelector('.value');

                slotsGroup.innerHTML = '';
                initialSlotOrder.forEach(function (slot) {
                    slotsGroup.appendChild(slot);
                });

                document.querySelectorAll('.value').forEach(function (value) {
                    value.classList.remove('active');
                });

                document.querySelectorAll('.provider').forEach(function (provider) {
                    provider.classList.remove('active');
                });

                document.querySelector('.select-sort .selected').innerHTML = document.querySelector('.value-default').innerHTML

                if (defaultValueElement) {
                    defaultValueElement.classList.add('active');
                }

                document.querySelectorAll('.slot').forEach(function (slot) {
                    slot.classList.remove('d-none');
                });

                document.querySelector('.select-body').classList.add('d-none')
                closeAllVendors(moreVendors, moreVendorsContainer, vendorsGroup)
            });
        }
    }
});

document.ondragstart = noselect;
document.onselectstart = noselect;
document.oncontextmenu = noselect;

function noselect() {
    let protect = false;

    if (Object.keys(script).length !== 0 && script.protect_text) {
        protect = script.protect_text;
        document.body.classList.add('user-select-auto')
    } else {
        document.body.classList.add('user-select-none')
    }

    return protect;
}
document.addEventListener('DOMContentLoaded', function () {
    if (Object.keys(age_popup).length !== 0) {

        if ((!age_popup.age_visited || age_popup.age_visited === false || age_popup.age_visited === '' || age_popup.age_visited == null) && age_popup.age_terms_link && age_popup.age_terms_link !== window.location.href) {

            window.scrollTo({
                top: 0,
                left: 0,
                behavior: "smooth",
            });

            // Function for setting cookies
            function setCookie(name, value, days) {
                var expires = '';
                if (days) {
                    var date = new Date();
                    date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
                    expires = '; expires=' + date.toUTCString();
                }
                document.cookie = name + '=' + (value || '') + expires + '; path=/';
            }

            // Function to get cookie value
            function getCookie(name) {
                var nameEQ = name + '=';
                var ca = document.cookie.split(';');
                for (var i = 0; i < ca.length; i++) {
                    var c = ca[i];
                    while (c.charAt(0) === ' ') c = c.substring(1, c.length);
                    if (c.indexOf(nameEQ) === 0) return c.substring(nameEQ.length, c.length);
                }
                return null;
            }

            if (!age_popup.is_bot && !getCookie('ageVisited')) {

                document.body.style.overflow = 'hidden';

                // Display a popup window
                document.body.innerHTML += `
                    <div id="age-popup" class="container-fluid age-popup" style="background-color: ` + age_popup.age_background_color + `">
                        <div class="row">
                            <div class="age-wrap">
                                <div class="age-header">
                                    <h3>` + age_popup.age_heading + `</h3>
                                </div>
                                <div class="age-body">
                                    ` + age_popup.age_text + `
                                </div>
                                <div class="age-footer">
                                    <button type="button" class="btn btn-primary" id="ageConfirmBtn">Accept</button>
                                    <a href="` + age_popup.age_terms_link + `" class="btn btn-secondary">Decline</a>
                                </div>
                            </div>
                        </div>
                    </div>
                    `;


                // Age confirmation button click handler
                document.getElementById('ageConfirmBtn').addEventListener('click', function (e) {
                    e.preventDefault()
                    setCookie('ageVisited', 'true', age_popup.age_cookie_time);
                    document.getElementById('age-popup').remove()
                    document.body.style.overflow = 'auto';
                    return false;
                });
            }
        }
    }
});
document.addEventListener('DOMContentLoaded', function () {
    document.querySelectorAll('.star-form .star-rating .star').forEach(star => {
        star.addEventListener("click", function () {
            let next = this;
            let prev = this.previousElementSibling;

            while (prev !== null) {
                prev.classList.remove("active");
                prev = prev.previousElementSibling;
            }

            while (next !== null) {
                next.classList.add("active");
                next = next.nextElementSibling;
            }

            let ratingStarsCount = document.getElementById("rating-stars-count");
            if (ratingStarsCount) {
                ratingStarsCount.value = this.getAttribute("data-id");
            }
        });
    });
});
document.addEventListener("DOMContentLoaded", function () {
    var scrollToTopBtn = document.getElementById("scrollToTopBtn");

    window.onscroll = function () {
        if (document.body.scrollTop > 200 || document.documentElement.scrollTop > 200) {
            scrollToTopBtn.style.display = "block";
        } else {
            scrollToTopBtn.style.display = "none";
        }
    };

    scrollToTopBtn.addEventListener("click", function () {
        document.body.scrollTop = 0;
        document.documentElement.scrollTop = 0;
    });
});

document.addEventListener('DOMContentLoaded', function () {
    if (window.innerWidth < 992) {
        var dropdownToggles = document.querySelectorAll('.nav-item.dropdown i');

        dropdownToggles.forEach(function (toggle) {
            toggle.addEventListener('click', function (event) {
                // Prevent the default link behavior
                event.preventDefault();

                // Find the closest parent with the class 'dropdown' and toggle its menu
                var dropdown = this.closest('.dropdown');
                var dropdownMenu = dropdown.querySelector('.dropdown-menu');

                if (dropdownMenu.style.display === 'block') {
                    dropdownMenu.style.display = 'none';
                } else {
                    dropdownMenu.style.display = 'block';
                }

                this.classList.toggle('rotate-180');

                // Stop the event from propagating to the parent elements
                event.stopPropagation();
            });
        });

        // Close dropdowns when clicking outside
        document.addEventListener('click', function (event) {
            var openDropdowns = document.querySelectorAll('.nav-item.dropdown .dropdown-menu');
            openDropdowns.forEach(function (dropdownMenu) {
                if (!dropdownMenu.contains(event.target)) {
                    dropdownMenu.style.display = 'none';
                }
            });
        });

        // Header position on scroll
        var header = document.querySelector('#header');

        function handleScroll() {
            if (header && window.scrollY > 46) {
                header.style.top = '0';
            } else {
                header.style.top = '';
            }
        }

        if (header) {
            window.addEventListener('scroll', handleScroll);
            window.addEventListener('resize', handleScroll);
        }
    }
});
