class SummaryWidget {

	/**
	 * @type {NodeListOf<Element>}
	 */
	scrollElements = document.querySelectorAll('.scrollto');

	/**
	 * @type {NodeListOf<Element>}
	 */
	scrollItem = document.querySelectorAll('.scroll_item');

	/**
	 *
	 * @type {Element}
	 */
	header = document.querySelector('.header');


	clickToLink() {
		this.scrollElements.forEach((el, key) => {
			let href = el.dataset.href;
			let targetElement = document.querySelector(href);

			el.addEventListener('click', (e) => {
				e.preventDefault();
				if (targetElement) {
					this.scrollToTarget(href)
				}
			});

			if (!targetElement) {
				this.scrollItem[key] ? this.scrollItem[key].remove() : null;
			}
		});
	}

	/**
	 *
	 * @param item
	 */
	scrollToTarget(item) {
		const itemTarget = decodeURIComponent(item);

		if (itemTarget) {
			const scrollTarget = document.querySelector(itemTarget);

			if (scrollTarget) {
				return window.scrollTo({
					top: scrollTarget.getBoundingClientRect().top + window.scrollY - this.header.offsetHeight,
					left: 0,
					behavior: 'smooth'
				});
			}
		}

		return console.warn(`Target element "${itemTarget}" not found.`);
	}
}

const summaryWidget = new SummaryWidget();
summaryWidget.clickToLink();


import {getOffersByClientLocation} from "api";
import {getVote, storeVote} from "voteApi";
import {navAff, utmParams as utmParamsSlotPlayAndDetails, eventID as eventIDSlotPlay} from "globals";

class SlotPlayAndDetailsWidget {
    /**
     *
     * @type {string}
     */
    currentUserGeo = document.body.dataset.geo;

    /**
     *
     * @returns {Promise<void>}
     */
    async previewCasino() {
        const slotPreview = document.querySelector(`.slot__preview--casino`);

        if (slotPreview) {
            const playNowButton = document.getElementById('playNowButton');
            const casinoData = await getOffersByClientLocation(this.currentUserGeo.toLowerCase());
            const casino = casinoData.slice()[0];

            let logo = document.createElement(`a`);
            logo.className = `logo_casino`;
            logo.style.backgroundColor = `#${casino.casino.background}`;
            logo.dataset.amplitude = "slotDemoPlayAffClick";

            let logoUrl = `${window.location.origin}/cdn/casino/logo/${casino.casino.domain}/logo.svg`;

            this.checkFileExistence(logoUrl)
                .then(fileExists => {
                    logoUrl = fileExists ? logoUrl : logoUrl.slice(0, -3) + 'png'
                    logo.style.backgroundImage = `url(${logoUrl})`;
                })
              . catch(err => console.log(err))

            this.openAffiliateLinkByClick(
                logo,
                casino
            );

            this.openAffiliateLinkByClick(
                playNowButton,
                casino
            );

            slotPreview.append(logo);
            this.slotDemoPlayAffClickFunc();

            this.slotAppendIconLoc(slotPreview, this.currentUserGeo.toLowerCase());
        }
    };

    /**
     *
     * @param url
     * @returns {Promise<boolean>}
     */
    checkFileExistence(url) {
        return fetch(url, {method: 'HEAD'})
            .then(response => {
                return response.status !== 200 ? false : true;
            })
    }

    /**
     *
     * @param element
     * @param loc
     */
    slotAppendIconLoc(element, loc) {
        if (loc !== 'nl' && loc !== 'us') {
            let country = document.createElement(`span`);
            country.className = `country_casino`;
            country.style.backgroundImage = `url(/build/img/flags/${loc}.svg)`;
            element.append(country);
        }
    }

    /**
     *
     * @returns {Promise<void>}
     */
    async setVoteClick() {
        const slotRatingStars = document.getElementById('slotRatingStars');

        let stars = slotRatingStars.querySelectorAll(`svg`);
        let vote = await getVote();

        this.setActiveStars(stars)

        if (vote.userVote) {
            this.userVoted(vote, stars, slotRatingStars);
        } else {
            if (vote.votes.length) {
                let countOfVoices = 0, medianOfVoices = 0;

                for (let key in vote.votes) {
                    countOfVoices += vote.votes[key].count;
                    medianOfVoices += vote.votes[key].value * vote.votes[key].count;
                }

                medianOfVoices /= countOfVoices;

                for (let i = 0; i < Math.round(medianOfVoices); i++) {
                    stars[i].dataset.name = `active`;
                }

                vote.innerHTML = `${Math.round(medianOfVoices)}/5 (${countOfVoices} vote${countOfVoices > 1 ? `s` : ``})`;
            }

            this.storeVoteClick(stars);
        }
    }

    /**
     *
     * @param elements
     */
    setActiveStars(elements) {
        Array.from(elements).forEach((star, index) => {
            star.addEventListener('mouseenter', () => {
                Array.from(elements).slice(0, index + 1).forEach(star => star.classList.add('active'));
            });

            star.addEventListener('mouseleave', () => {
                Array.from(elements).forEach(star => star.classList.remove('active'));
            });
        });
    }

    /**
     *
     * @param elements
     */
    storeVoteClick(elements) {
        elements.forEach((star, index) => {
            star.addEventListener('click', async () => {
                let votedData = await storeVote(index + 1);

                this.userVoted(votedData);
            });
        });
    }

    /**
     *
     * @param data
     */
    userVoted(data) {
        const slotRatingStars = document.getElementById('slotRatingStars');
        const ratings = document.getElementsByClassName('rating');
        const votes = document.getElementById('slotRatingVotes');

        let countOfVoices = 0;
        let medianOfVoices = 0;

        for (const key in data.votes) {
            countOfVoices += data.votes[key].count;
            medianOfVoices += data.votes[key].value * data.votes[key].count;
        }

        for (let i = 0; i < Math.round(medianOfVoices); i++) {
            ratings[i].classList.add('active');
        }

        medianOfVoices /= countOfVoices;
        votes.innerHTML = `${Math.round(medianOfVoices)}/5 (${countOfVoices} vote${countOfVoices > 1 ? 's' : ''})`;

        slotRatingStars.classList.add('selected');
        slotRatingStars.style.pointerEvents = 'none';
    }

    /**
     *
     * @param styles
     */
    toggleDialogAnimation(styles) {
        styles['modal_button'] ? styles['modal_button'].addEventListener('click', () => {
            styles['modal'].style.animation = 'scaleDialogOpen 0.5s ease-in-out forwards';
            this.appendMobileBgShadow();
        }) : null;

        styles['modal_close'] ? styles['modal_close'].addEventListener('click', () => {
            styles['modal'].style.animation = 'scaleDialogClose 0.5s ease-in-out forwards';
            this.removeMobileBgShadow();
        }) : null;
    }

    /**
     *
     * @param element
     * @param casino
     */
    openAffiliateLinkByClick(element, casino) {
        element ? element.addEventListener(`click`, e => {
            e.preventDefault();
            navAff(`${casino.casino.domain}?bonus=${casino.id}`, true, '', casino.affiliateUrl, casino.casino.domain);
        }) : null;
    }

    appendMobileBgShadow() {
        const existingBgShadow = document.getElementById('backgroundShadow');

        if (!existingBgShadow) {
            const slotPlayDetails = document.getElementById('slotPlayDetails');

            let html = `
                <div id="backgroundShadow" class="background_shadow"></div>
            `;

            slotPlayDetails.insertAdjacentHTML('beforeend', html);
        }
    }

    // slotDemoPlayAffClick
    slotDemoPlayAffClickFunc = () => {
        const slotDemoPlayAffClick = document.querySelectorAll(`[data-amplitude="slotDemoPlayAffClick"]`);

        if (slotDemoPlayAffClick.length) {
            const slotData = document.querySelector(`.slot__preview--links`);
            const slotDataset = slotData.dataset;
            const btnTextItem = slotDataset.casinoBonusButtonName;

            let widgetAffLinkClickIndex = 0;

            slotDemoPlayAffClick.forEach(item => {
                const widget = item.closest(`.slotPlayDetails`);
                const widgetHandler = widget.dataset.widgetHandler;
                const widgetPosition = widget.dataset.widgetPosition;
                const widgetSection = widget.dataset.widgetSection;

                item.addEventListener(`click`, () => {

                    const casinoData = {
                        widgetTitle: `slotDemoPlay`,
                        eventCat: "w_slot_demo_play",
                        widgetPref: "showBlock",
                        clickAffLinkVersion: 35,
                        showWidgetVersion: 34,
                        eventAffClickName: "casino_visit",
                        casinos: [slotDataset],
                        casino: slotDataset,
                        btnText: btnTextItem
                    };

                    widgetAffLinkClickIndex++;

                    let {casino, widgetTitle, eventCat, clickAffLinkVersion, eventAffClickName, btnText} = casinoData;

                    const PAGE__CURRENT__PATH = document.location.pathname,
                        PAGE__URL = document.location.origin + document.location.pathname,
                        PAGE__URL__FULL = document.location.href,
                        ROUTE = document.body.dataset.routeBonus,
                        ROUTE__ID = document.body.dataset.routeId,
                        ROUTE__EXIST = eventIDSlotPlay.findIndex(item => item === ROUTE),
                        EVENT__ID = ROUTE__EXIST > -1 ? ROUTE__EXIST + 1 : eventIDSlotPlay.length,
                        EVENT__CAT = ROUTE__EXIST > -1 ? eventIDSlotPlay[ROUTE__EXIST] : eventIDSlotPlay[eventIDSlotPlay.length - 1],
                        LOCALE__LANG = document.body.dataset.localeLang,
                        WEBSITE__ENVIRONMENT = document.body.dataset.websiteEnv,
                        LOCALE__COUNTRY = document.body.dataset.localeCountry,
                        COUNTRY__BACKEND = document.body.dataset.geo;

                    let pageAffLinkClickIndex = storage.getPageAffLinkClickIndex();
                    pageAffLinkClickIndex++;
                    storage.setPageAffLinkClickIndex(pageAffLinkClickIndex);

                    if (!casino.casino) casino.casino = {}

                    let casino_bonus_days_after_create = 0;
                    if (item.created) {
                        const createdDate = new Date(item.created.date);
                        const currentDate = new Date();
                        const diffTime = Math.abs(currentDate - createdDate);
                        casino_bonus_days_after_create = Math.floor(diffTime / (1000 * 60 * 60 * 24));
                    }

                    dataLayer && dataLayer.push(Object.assign({
                        'event': 'addEvents_clickAffLink',
                        'event_id': `d-v${document.body.dataset.amplitudeVersion}-e${clickAffLinkVersion}`,
                        'event_cat': eventCat,
                        'event_name': eventAffClickName,
                        "page_current_path": JSON.stringify(PAGE__CURRENT__PATH),
                        "page_url": JSON.stringify(PAGE__URL),
                        "page_url_full": JSON.stringify(PAGE__URL__FULL),
                        "page_group": JSON.stringify(EVENT__CAT),
                        "widget_title": JSON.stringify(widgetTitle),
                        "widget_id": JSON.stringify(null),
                        "page_route_id": JSON.stringify(ROUTE__ID),
                        "widget_handler": JSON.stringify(widgetHandler),
                        "widget_section": JSON.stringify(widgetSection),
                        "widget_position": JSON.stringify(widgetPosition),
                        "casino_list_user_country": JSON.stringify(COUNTRY__BACKEND),
                        "casino_user_country": JSON.stringify(COUNTRY__BACKEND),
                        "casino_list_for_geo": JSON.stringify(false),
                        "casino_domain": JSON.stringify(casino.domain),
                        "casino_bonus_id": JSON.stringify(casino.bonus),
                        "casino_name": JSON.stringify(casino.name),
                        "casino_bonus_amount_max": JSON.stringify(casino.amountMax && !isNaN(parseInt(casino.amountMax)) ? parseInt(casino.amountMax) : 0),
                        "casino_bonus_percent": JSON.stringify(casino.percent ? casino.percent : 0),
                        "casino_bonus_expired": JSON.stringify(casino.expired ? casino.expired : false),
                        "casino_bonus_button_name": JSON.stringify(btnText),
                        "casino_geo_rating": JSON.stringify(casino.casinoGeoRating ? casino.casinoGeoRating : 0),
                        "casino_bonus_title_short": JSON.stringify(casino.titleShort),
                        "casino_afflink_exist": JSON.stringify(!!casino.affiliate),
                        "casino_bonus_wagering_requirements": JSON.stringify(casino.wageringRequirements && !isNaN(parseInt(casino.wageringRequirements)) ? parseInt(casino.wageringRequirements) : 0),
                        "casino_bonus_deposit_min": JSON.stringify(casino.depositMin ? parseInt(casino.depositMin) : 0),
                        "casino_bonus_category": JSON.stringify(casino.bonusCategories ? casino.bonusCategories : null),
                        "casino_bonus_label": JSON.stringify(casino.label ? casino.label : "Not Set"),
                        "widget_list_index": JSON.stringify(1),
                        "casino_bonus_type": JSON.stringify(casino.bonusTypes ? casino.bonusTypes : null),
                        "casino_bonus_free_spins": JSON.stringify(casino.freeSpins ? +casino.freeSpins : 0),
                        "page_afflink_click_index": JSON.stringify(pageAffLinkClickIndex),
                        "widget_afflink_click_index": JSON.stringify(widgetAffLinkClickIndex),
                        "casino_user_country_allowed": JSON.stringify(true),
                        "casino_bonus_currency": JSON.stringify(casino.currency ? casino.currency : ["Not Set"]),
                        "casino_bonus_active": JSON.stringify(casino.affiliate ? true : false),
                        "casino_bonus_slots": JSON.stringify(casino.bonusSlots ? casino.bonusSlots : ["Not Set"]),
                        "casino_bonus_category_display": JSON.stringify(casino.casinoBonusCategoryDisplay ? casino.casinoBonusCategoryDisplay : "Not Set"),
                        "casino_bonus_active_days_left": JSON.stringify(casino.casino_bonus_active_days_left),
                        "casino_bonus_days_after_create": JSON.stringify(casino.casino_bonus_days_after_create),
                        "casino_bonus_cashable": JSON.stringify(casino.casinoBonusCashable ? casino.casinoBonusCashable : false),
                        "casino_bonus_code": JSON.stringify(casino.casinoBonusCode ? casino.casinoBonusCode : "Not Set"),
                        "sponsored": JSON.stringify(casino.sponsored ? true : false)
                    }, utmParamsSlotPlayAndDetails()));


                })
            })
        }
    }

    // slotDemoPlayAffClick

    removeMobileBgShadow() {
        const backgroundShadow = document.getElementById('backgroundShadow');

        backgroundShadow ? backgroundShadow.remove() : null;
    }

    appendIframeClick() {
        let slotPlayFree = document.getElementById('slot__playFreeCasino');

        if (slotPlayFree) {
            slotPlayFree.addEventListener('click', e => {
                const slotPreviewLinks = document.getElementById('slotPreviewLinks');
                let slotPreview = document.getElementById('fullScreenDemoPreview');
                let iframeContainer = slotPreview.querySelector('#iframeContainer');
                iframeContainer.innerHTML = `<iframe frameborder="0" allowfullscreen="" mozallowfullscreen="" webkitallowfullscreen="" hspace="0" vspace="0" scrolling="none" src="${e.target.dataset.url}" width="100%" height="100%"></iframe>`;
                slotPreview.classList.add('show--iframe');
                slotPlayFree.remove();
                slotPreviewLinks.remove();
            });
        }
    }

    setFullScreenClick() {
        const slotFullScreen = document.getElementById('slotFullScreen');
        const fullScreenDemo = document.getElementById('fullScreenDemo');
        const fullScreenDemoPreview = document.getElementById('fullScreenDemoPreview');

        slotFullScreen.addEventListener('click', () => {
            if (!document.fullscreenElement && !document.mozFullScreenElement && !document.webkitFullscreenElement && !document.msFullscreenElement) {

                const requestFullScreen = fullScreenDemo.requestFullscreen || fullScreenDemo.mozRequestFullScreen || fullScreenDemo.webkitRequestFullscreen || fullScreenDemo.msRequestFullscreen;

                if (requestFullScreen) {
                    requestFullScreen.call(fullScreenDemo);
                    fullScreenDemoPreview.style.maxHeight = '100vh';
                    fullScreenDemoPreview.style.height = '100vh';
                }
            } else {
                const exitFullScreen = document.exitFullscreen || document.mozCancelFullScreen || document.webkitExitFullscreen || document.msExitFullscreen;

                if (exitFullScreen) {
                    exitFullScreen.call(document);
                    fullScreenDemoPreview.style.height = '';
                    fullScreenDemoPreview.style.maxHeight = '685px';
                }
            }
        });
    }

    copyEmbedCodeClick() {
        const copyEmbedCode = document.getElementById('copyEmbedCode');
        const copyEmbedCodeButton = document.getElementById('copyEmbedCodeButton');

        if (copyEmbedCodeButton) {
            copyEmbedCodeButton.addEventListener('click', () => {
                copyEmbedCode.select();
                document.execCommand("copy");
                copyEmbedCodeButton.innerHTML = 'Copied!';
                setTimeout(() => copyEmbedCodeButton.innerHTML = 'Copy', 2000);
            });
        }
    }

    openCopyCodeModalToggleClick() {
        const copyCodeModal = document.getElementById('copyCodeModal');
        const copyCodeModalClose = document.getElementById('copyCodeModalClose');
        const copyCodeModalButton = document.getElementById('copyCodeModalButton');

        this.toggleDialogAnimation({
            'modal': copyCodeModal, 'modal_close': copyCodeModalClose, 'modal_button': copyCodeModalButton
        });
    }
}

const slotPlayAndDetailsWidget = new SlotPlayAndDetailsWidget;

slotPlayAndDetailsWidget.setVoteClick();
slotPlayAndDetailsWidget.previewCasino();
slotPlayAndDetailsWidget.copyEmbedCodeClick();
slotPlayAndDetailsWidget.setFullScreenClick();
slotPlayAndDetailsWidget.appendIframeClick();
slotPlayAndDetailsWidget.openCopyCodeModalToggleClick();


import {getTermsAndConditions} from "api";
import {navAff as bonusCategoryNavAff} from "globals";

class BonusCategoryWidget {

	/**
	 *
	 * @type {NodeListOf<Element>}
	 */
	bonusCards = document.querySelectorAll('.table_cards-card[data-expired="false"]');

	/**
	 *
	 * @type {NodeListOf<Element>}
	 */
	bonusCardsSidebar = document.querySelectorAll(`.table_cards-card.half-hide`);

	/**
	 *
	 * @type {NodeListOf<Element>}
	 */
	casinoReviewLink = document.querySelectorAll(`.card-casino-review`);

	/**
	 *
	 * @type {Element}
	 */
	firstBonusTableTitle = document.querySelector('.bonusCardsTableWidget .widget-title');

	/**
	 *
	 * @type {[string]}
	 */
	tncCountries = [`GB`];

	/**
	 *
	 * @type {NodeListOf<Element>}
	 */
	showMoreBtn = document.querySelectorAll(`button.table-show-more`);

	/**
	 *
	 * @type {NodeListOf<Element>}
	 */
	bonusCardsTnc = document.querySelectorAll('.card-terms');

	/**
	 *
	 * @type {NodeListOf<Element>}
	 */
	bonusCardsTncText = document.querySelectorAll('.card-terms-block');

	/**
	 *
	 * @type {HTMLCollectionOf<Element>}
	 */
	promoCode = document.querySelectorAll('.promo_code-block');

	/**
	 *
	 * @param element
	 * @returns {Promise<void>}
	 */
	copyText(element) {
		return navigator.clipboard.writeText(element);
	}

	/**
	 *
	 * @param item
	 * @param index
	 */
	affiliateRedirectItem(item, index) {
		let url = item.dataset.domain + `?bonus=${item.dataset.bonus}`;
		let blank = true;
		let events = {
			'event': 'TrackOffersClickMainBonusesTableAffiliateLink',
			'eventCategory': 'TrackOffers',
			'eventAction': 'ClickMainBonusesTableAffiliateLink',
			'eventLabel': item.dataset.domain,
			'eventValue': index + 1
		};
		let restricted = item.dataset.restricted;
		let affLink = item.dataset.affiliate;

		bonusCategoryNavAff(url, blank, events, restricted, affLink)
	}

	reviewLinks() {
		this.casinoReviewLink.forEach((item, index) => {
			item.addEventListener(`click`, e => {
				e.stopPropagation();

				let bonus = item.closest(`.table_cards-card`);
				let path = bonus.dataset.path;
				let url = `/${path}/${bonus.dataset.domain}`;
				let blank = false;
				let events = {
					'event': 'TrackNavClickMainBonusesTableCasinoReviewLink',
					'eventCategory': 'TrackNav',
					'eventAction': 'ClickMainBonusesTableCasinoReviewLink',
					'eventLabel': url,
					'eventValue': index + 1
				};
				let restricted = false;
				let affLink = `review`;

				bonusCategoryNavAff(url, blank, events, restricted, affLink);
			});
		})
	}

	affiliateRedirect() {
		this.bonusCards.forEach((item, index) => {
			item.addEventListener(`click`, () => this.affiliateRedirectItem(item, index));
		});
	}

	onClickTncLoop() {
		this.bonusCardsTnc.forEach(item => {
			item.addEventListener(`click`, async e => {
				e.stopPropagation();

				setTimeout(async () => {
					let tncBtnText = item.querySelector(`span`);
					let bonus = item.closest(`.table_cards-card`);
					let bonusId = bonus.dataset.bonus;
					let tncText = bonus.querySelector(`.card-terms-block`);

					if (!item.classList.contains(`shown`)) {
						if (!tncText.innerHTML) {
							let result = await getTermsAndConditions(bonusId);
							tncText.innerHTML = result ? result : `18+. New players only. General withdrawal restrictions & full T&Cs apply.`;
						}

						tncBtnText.dataset.textBefore = `Hide T&C`;
					} else {
						tncBtnText.dataset.textBefore = `Show T&C`;
					}

					tncText.classList.toggle(`shown`);
					item.classList.toggle(`shown`);
				}, 100);
			})
		})
	}

	tncShow() {
		let loc = document.body.dataset.geo;

		if (this.tncCountries.includes(loc)) {
			this.bonusCardsTnc.forEach(async item => {
				let tncBtnText = item.querySelector(`span`);
				let bonus = item.closest(`.table_cards-card`);
				let bonusId = bonus.dataset.bonus;
				let tncText = bonus.querySelector(`.card-terms-block`);

				if (!tncText.innerHTML) {
					let result = await getTermsAndConditions(bonusId);
					tncText.innerHTML = result ? result : `18+. New players only. General withdrawal restrictions & full T&Cs apply.`;
				}

				tncBtnText.dataset.textBefore = `Hide T&C`;

				tncText.classList.add(`shown`);
				item.classList.add(`shown`);
			});
		}
	}

	onClickTncText() {
		let loc = document.body.dataset.geo;

		if (this.tncCountries.includes(loc)) {
			this.bonusCardsTncText.forEach(item => {
				let termsUrl = item.dataset.termsUrl;

				termsUrl && item.addEventListener(`click`, e => {
					e.stopPropagation();
					window.open(item.dataset.termsUrl, `_blank`);
				})
			})
		}
	}

	onClickPromoCodeLoop() {
		this.promoCode.forEach(item => {
			item.addEventListener(`click`, e => {
				e.stopPropagation();
				let text = item.querySelector(`.promo_code-text`).dataset.textBefore;

				this.copyText(text).then(() => {
					item.classList.contains(`copied`) && item.classList.remove(`copied`);
					item.classList.add(`coping`);
					setTimeout(() => {
						item.classList.remove(`coping`);
						item.classList.add(`copied`);
					}, 1500)
				});
			})
		})
	}

	generateTooltip() {
		if (this.firstBonusTableTitle) {
			const disclaimerWrapper = document.createElement('div');
			const disclaimerTemplate = document.createElement('div');

			disclaimerWrapper.classList.add('bonus_disclaimer_wrapper');
			disclaimerTemplate.classList.add('bonus_disclaimer')

			disclaimerTemplate.innerHTML = `<div class="bonus_disclaimer--title">Ad disclaimer</div>
            <div class="bonus_disclaimer_popup">
                <div class="bonus_disclaimer_popup--text">
                    Casinos Analyzer provides you with thorough reviews of world's largest casino sites. With the help of the partners Casinos Analyzer gets the income with the commissions. Despite this, gaming experience of a User is not affected by commissions that we receive. Nevertheless, we give only honest reviews which correspond to our standards.
                </div>
                <div class="bonus_disclaimer_popup--close">
                    <svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                    <path d="M12 11.1113L15.1113 8L16 8.88875L12.8887 12L16 15.1113L15.1113 16L12 12.8887L8.88875 16L8 15.1113L11.1113 12L8 8.88875L8.88875 8L12 11.1113Z" fill="#B5B5B5"/>
                    </svg>
                </div>
             </div>`;

			this.firstBonusTableTitle.parentNode.insertBefore(disclaimerWrapper, this.firstBonusTableTitle);

			disclaimerWrapper.appendChild(this.firstBonusTableTitle);
			disclaimerWrapper.appendChild(disclaimerTemplate);

			const disclaimerPopup = disclaimerTemplate.querySelector('.bonus_disclaimer_popup');


			if (window.innerWidth >= 1200) {
				disclaimerTemplate.addEventListener('mouseenter', e => {
					disclaimerPopup.classList.add('show');
				})
				disclaimerTemplate.addEventListener('mouseleave', e => {
					disclaimerPopup.classList.remove('show');
				})
			} else {
				this.generateMobileTooltip(disclaimerPopup)
			}
		}
	}

	generateMobileTooltip(disclaimerPopup) {
		document.addEventListener('click', e => {
			const {target} = e;

			if (target.closest('.bonus_disclaimer--title')) {
				if (disclaimerPopup.classList.contains('show')) {
					return;
				}
				disclaimerPopup.classList.add('show');
			} else if (target.closest('.bonus_disclaimer_popup--close') || !target.closest('.bonus_disclaimer_popup')) {
				disclaimerPopup.classList.remove('show')
			}
		})
	}

	showMore() {
		if (this.showMoreBtn.length) {
			this.showMoreBtn.forEach(btn => {
				btn.addEventListener(`click`, () => {
					let trs = [...btn.parentNode.querySelectorAll(`tr`)],
						hidden = trs.filter(tr => tr.classList.contains(`hide`)),
						count = btn.dataset.count;

					if (hidden.length > 0) {
						hidden.splice(0, count).forEach(tr => tr.classList.remove(`hide`));
						hidden = trs.filter(tr => tr.classList.contains(`hide`));

						if (hidden.length < count) btn.innerHTML = `${btn.dataset.text} (+${hidden.length})`;

						hidden.length <= 0 && btn.remove();
					} else {
						btn.remove();
					}
				})
			})
		}
	}

	bonusCardsSidebarToggle() {
		if (this.bonusCardsSidebar.length) {
			this.bonusCardsSidebar.forEach((item, index) => {
				let header = item.querySelector(`.card-td-header`);
				header.addEventListener(`click`, e => {
					e.stopPropagation();

					item.classList.toggle(`half-hide`);
				})
			})
		}
	}

	onLoadStopPromoCodeAnimation() {
		Array.from(this.promoCode).forEach((element) => {
			const codeWrapper = element.querySelector('.promo_code-text-wrapper');
			const codeText = element.querySelector('.promo_code-text');
			if (typeof (codeText) !== 'undefined' && codeText !== null && typeof (codeWrapper) != 'undefined' && codeWrapper !== null) {
				const cs = getComputedStyle(codeWrapper);
				const paddingX = parseFloat(cs.paddingLeft) + parseFloat(cs.paddingRight);
				if (codeText.offsetWidth <= codeWrapper.offsetWidth - paddingX) {
					codeText.style.animation = 'unset';
					codeWrapper.classList.add(`unsetAnimation`);
				}
			}
		});
	}
}

const bonusWidget = new BonusCategoryWidget();

window.addEventListener('load', () => {
	bonusWidget.onClickPromoCodeLoop();
	bonusWidget.generateTooltip();
	bonusWidget.onClickTncLoop();
	bonusWidget.tncShow();
	bonusWidget.onClickTncText();
	bonusWidget.bonusCardsSidebarToggle();
	bonusWidget.affiliateRedirect();
	bonusWidget.reviewLinks();
	bonusWidget.showMore();
	bonusWidget.onLoadStopPromoCodeAnimation();
});






import {appendStaticContentCarousel} from "/build/midori/assets/js/staticContentCarousel.js";

document.addEventListener('DOMContentLoaded', () => {
    appendStaticContentCarousel();
});




import {fadeOut, fadeIn} from "globals";

let summaryBtn = document.querySelectorAll('.table-of-content__dropdown__button');

summaryBtn.forEach(el => {
	el.addEventListener('click', e => {
		e.stopPropagation();

		let summaryBlock = el.nextElementSibling;

		if (el.classList.contains(`active`)) {
			el.classList.remove(`active`);
			fadeOut(summaryBlock);
		} else {
			el.classList.add(`active`);
			fadeIn(summaryBlock);
		}
	})
});

window.addEventListener(`click`, () => {
	let summaryBlockActive = document.querySelector('.table-of-content__dropdown__button.active');

	if (summaryBlockActive) {
		summaryBlockActive.classList.remove(`active`);
		fadeOut(summaryBlockActive.nextElementSibling);
	}
})


import {__translate as __cspw_translate} from "translate";
import {getLocaleCountry as __cspw_localeCountry} from "globals";

class CasinoSoftwareProviderWidget {

	moreBtns = Array.from(document.querySelectorAll('.casinoSoftwareProviderWidget__providers--btn'));
	items = Array.from(document.querySelectorAll('.casinoSoftwareProviderWidget__providers--item.hide'))

	moreBtnClick() {
		if (this.moreBtns.length > 0) {
			this.moreBtns.forEach(el => {
				el.addEventListener('click', () => {
					this.showHideItems()
					this.moreLessBtnTxt(el)
				})
			})
		}
	}

	showHideItems() {
		if (this.items.length > 0) {
			this.items.forEach(el => {
				if (el.classList.contains('hide')) {
					el.classList.remove('hide');
					el.classList.add('show');
				} else {
					el.classList.remove('show');
					el.classList.add('hide');
				}
			})
		}
	}

	moreLessBtnTxt(currentBtn) {
		let currentWrapper = currentBtn.closest('.casinoSoftwareProviderWidget__providers');
		let currentBtnTxt = currentBtn.querySelector('.casinoSoftwareProviderWidget__providers--item-others span');
		if (currentBtn.classList.contains('more')) {
			currentBtn.classList.remove('more')
			currentBtnTxt.innerHTML = `${__cspw_translate('Show Less', __cspw_localeCountry()) ?? 'Show Less'}`;
		} else {
			currentBtn.classList.add('more');
			currentBtnTxt.innerHTML = 'Others (' + (currentWrapper.dataset.count - 5) + ')';
		}
	}
}

const casinoSoftwareProviderWidget = new CasinoSoftwareProviderWidget;

document.addEventListener('DOMContentLoaded', () => {
	casinoSoftwareProviderWidget.moreBtnClick();
})


class ScrollButtonWidget {
    header = document.querySelector('.header');
    scrollButton = document.querySelectorAll('.scrollButtonWidget__btn');

    scrollButtonClick() {
        if (this.scrollButton) {
            this.scrollButton.forEach(item => {
                item.addEventListener('click', (e) => {
                    e.preventDefault();
                    let scrollButtonTarget = item.dataset.target;
                    let blockToScrollDataId = document.querySelector(`[data-id="${scrollButtonTarget}"]`);
                    let blockToScrollId = document.querySelector(`#${scrollButtonTarget}`);

                    scrollButtonTarget = blockToScrollId ? blockToScrollId : blockToScrollDataId ? blockToScrollDataId : this.firstBlock();

                    if (!scrollButtonTarget) {
                        return;
                    }

                    const scrollButtonTargetOffset = scrollButtonTarget.getBoundingClientRect().top

                    setTimeout(() => {
                        window.scroll({
                            top: scrollButtonTargetOffset + (window.scrollY - this.header.offsetHeight),
                            behavior: 'smooth'
                        });
                    }, 100);
                })
            })
        }
    }

    firstBlock() {
        for (let i = 1; i <= 100; i++) {
            let elementId = "block_" + i;
            let element = document.querySelector(`[data-id="${elementId}"]`);

            if (element) {
                return element;
            }
        }
        return null
    }
}

const scrollButtonWidget = new ScrollButtonWidget();

scrollButtonWidget.scrollButtonClick();



import {elementInViewport, utmParams as utmParamsTestimonial, eventID as eventIDTestimonial} from "globals";
import {__translate as __tw_translate } from "translate";

const allFiles = [];

const headerHeight = document.querySelector('.header').offsetHeight;

const filesManager = (dropzoneElement, files) => {
	files = [...files];

	let dropzoneGallery = dropzoneElement.querySelector('.testimonialWidget__form__dropzone__gallery');
	let dropzoneWrapper = dropzoneElement.querySelector('.testimonialWidget__form__dropzone__wrapper');
	let dropzoneGalleryAdd = dropzoneElement.querySelector('.testimonialWidget__form__dropzone__add');
	let dropzoneError = dropzoneElement.querySelector('.testimonialWidget__form__error');

	if (dropzoneError) {
		dropzoneError.remove();
	}

	if (!dropzoneGalleryAdd) {
		let dropzoneWrapperInput = dropzoneWrapper.querySelector('input[type="file"]');

		let dropzoneGalleryAddImg = document.createElement('div');
		dropzoneGalleryAddImg.classList.add('testimonialWidget__form__dropzone__add--img');
		dropzoneGalleryAddImg.innerHTML = `<svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
            <path d="M11 11V5H13V11H19V13H13V19H11V13H5V11H11Z" fill="#5554DE"/>
        </svg>`;

		dropzoneGalleryAdd = document.createElement('div');
		dropzoneGalleryAdd.classList.add('testimonialWidget__form__dropzone__add')

		dropzoneGalleryAdd.appendChild(dropzoneGalleryAddImg);
		dropzoneGalleryAdd.appendChild(dropzoneWrapperInput);
		dropzoneWrapper.remove();
	}

	if (!dropzoneGallery) {
		dropzoneGallery = document.createElement("div");
		dropzoneGallery.classList.add("testimonialWidget__form__dropzone__gallery");

		let dropzoneGalleryTitle = document.createElement('div');
		dropzoneGalleryTitle.classList.add('testimonialWidget__form__dropzone__gallery--title');
		dropzoneGalleryTitle.innerHTML = 'This is never published, but to validate that you are a real player at that casino';

		dropzoneGallery.appendChild(dropzoneGalleryAdd);
		dropzoneElement.appendChild(dropzoneGalleryTitle);
		dropzoneElement.appendChild(dropzoneGallery);
	}

	files.forEach((el) => {
		if (fileValidationExt(el)) {
			allFiles.push(el);
			previewFile(el, dropzoneGallery);
		} else {
			console.log('Your file ' + el.name + ' has unsupported extension');
		}
	})
}

const fileValidationExt = (file) => {
	const extension = file.name.split('.').pop();
	const allowedExtensions = ["jpg", "jpeg", "bmp", "gif", "png", "tiff", "webp"];
	return allowedExtensions.includes(extension);
}

const previewFile = (file, dropzoneGallery) => {
	let fileReader = new FileReader();
	fileReader.readAsDataURL(file);

	fileReader.onloadend = () => {
		let dropzoneThumbItem = document.createElement('div');
		dropzoneThumbItem.classList.add('testimonialWidget__form__dropzone__thumb');
		dropzoneThumbItem.dataset.lastModified = file.lastModified;


		let dropzoneThumbImg = document.createElement('img');
		dropzoneThumbImg.classList.add('testimonialWidget__form__dropzone__thumb--img');

		let dropzoneThumbClose = document.createElement('div');
		dropzoneThumbClose.classList.add('testimonialWidget__form__dropzone__thumb--close');

		dropzoneThumbImg.src = fileReader.result;
		dropzoneThumbImg.setAttribute('data-name', file.name);
		dropzoneThumbClose.innerHTML = `<svg width="10" height="10" viewBox="0 0 10 10" fill="none" xmlns="http://www.w3.org/2000/svg">
                <path d="M4.99981 4.08352L8.20815 0.875183L9.12463 1.79166L5.9163 5L9.12463 8.20833L8.20815 9.12481L4.99981 5.91648L1.79148 9.12481L0.875 8.20833L4.08333 5L0.875 1.79166L1.79148 0.875183L4.99981 4.08352Z" fill="#FF455B"/>
            </svg>`;

		dropzoneThumbItem.appendChild(dropzoneThumbImg);
		dropzoneThumbItem.appendChild(dropzoneThumbClose);
		dropzoneGallery.prepend(dropzoneThumbItem);
	}
}

const manageDrop = (dropzoneElement, e) => {
	let dataTrans = e.dataTransfer;
	let files = dataTrans.files;
	filesManager(dropzoneElement, files)
}

const validateAllFields = (form) => {

	const formData = new Map([
		['name', form.querySelector('input[name="name"]')],
		['email', form.querySelector('input[name="email"]')],
		['rating', form.querySelectorAll('input[name="rating"]')],
		['liked', form.querySelector('textarea[name="liked"]')],
		['notLiked', form.querySelector('textarea[name="not_liked"]')]
	]);

	let fieldsValid = true;

	formData.forEach(function (item, key) {
		let itemVal, message;

		if (key != 'rating') {
			itemVal = item.value.trim();
		} else {
			itemVal = starsWrapper.dataset.value;
			item = form.querySelector('.testimonialWidget__form__radio--wrapper');
		}

		if (!itemVal || itemVal === '') {
			setError(item, createErrorMessage(key));
			fieldsValid = false;
		} else if (key == 'email' && !isValidEmail(itemVal)) {
			setError(item, 'Provide a valid email address');
			fieldsValid = false;
		} else {
			setSuccess(item);
		}
	});

	return fieldsValid;
}

const createErrorMessage = (input) => {
	let message;
	switch (input) {
		case 'name':
			message = 'The name field is required';
			break;
		case 'email':
			message = 'Email is required';
			break;
		default:
			message = 'Please fill in this input';
	}
	return message;
}

const setError = (element, message) => {
	const inputControl = element;
	let errorDisplay = element.parentElement.querySelector('.testimonialWidget__form__error')

	if (!errorDisplay) {
		errorDisplay = document.createElement('div');
		errorDisplay.classList.add('testimonialWidget__form__error');
	}
	errorDisplay.innerText = message;

	inputControl.parentElement.appendChild(errorDisplay);
	inputControl.classList.add('invalid');
}

const setSuccess = (element) => {
	const inputControl = element;
	const errorElement = element.parentElement.querySelector('.testimonialWidget__form__error');
	if (errorElement) {
		errorElement.remove();
	}

	inputControl.classList.remove('invalid');
}

const isValidEmail = (email) => {
	const re = /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;

	return re.test(String(email).toLowerCase());
}

const submitForm = (form) => {
	const LOCALE_COUNTRY = document.querySelector(`body`).dataset.localeCountry.toLowerCase();
	const formWrapper = form.closest('.testimonialWidget__form');

	formWrapper.innerHTML = `<div class="testimonialWidget__form__success">
        <div class="testimonialWidget__form__success--logo">
            <svg width="41" height="40" viewBox="0 0 41 40" fill="none" xmlns="http://www.w3.org/2000/svg">
                <path d="M16.7498 24.9028L32.9987 8.33331L35.5 10.8819L16.7498 30L5.5 18.5295L7.99956 15.9809L16.7498 24.9028Z" fill="#5554DE"/>
            </svg>
        </div>
        <div class="testimonialWidget__form__success--title">${__tw_translate("Thank you! Your review has been successfully sent", LOCALE_COUNTRY)}</div>
        <div class="testimonialWidget__form__success--description">${__tw_translate("Moderation may take up to 24 hours. We will let you know via e-mail when it’s published", LOCALE_COUNTRY)}</div>
        <button class="testimonialWidget__form__success--btn">${__tw_translate("Go to bonuses", LOCALE_COUNTRY)}</button>
    </div>`;

	formWrapper.querySelector('.testimonialWidget__form__success--btn').addEventListener('click', () => {
		const bonusTableOffsetTop = document.querySelector('.bonusCardsTableWidget')?.getBoundingClientRect().top || 0;
		const headerOffsetHeight = document.querySelector('.header')?.getBoundingClientRect()?.height || document.querySelector('.stickyWidget')?.getBoundingClientRect()?.height || 0;

		window.scrollTo({
			top: bonusTableOffsetTop + (window.scrollY - headerOffsetHeight),
			behavior: 'smooth'
		});
	});

	formWrapper.scrollIntoView({
		block: 'center',
		inline: 'center'
	});
}

const starsWrapper = document.querySelector(`.testimonialWidget__form__radio--stars`);
const stars = document.querySelectorAll(`.testimonialWidget__form__radio--star`);
stars.forEach(star => {
	star.addEventListener(`click`, () => {
		let forAttr = star.getAttribute(`for`);
		let inputValue = document.querySelector(`input#${forAttr}`).value;
		starsWrapper.dataset.value = inputValue;

		stars.forEach((v, i) => {
			i < inputValue ? v.classList.add('radio_star-active') : v.classList.remove('radio_star-active');
		});
	})
})

const amplitudeTestimonial = () => {
	const ROUTE = document.body.dataset.routeBonus;
	const ROUTE__ID = document.body.dataset.routeId;
	const ROUTE__EXIST = eventIDTestimonial.findIndex(item => item === ROUTE);
	const EVENT__ID = ROUTE__EXIST > -1 ? ROUTE__EXIST + 1 : eventIDTestimonial.length;
	const EVENT__CAT = ROUTE__EXIST > -1 ? eventIDTestimonial[ROUTE__EXIST] : eventIDTestimonial[eventIDTestimonial.length - 1];

	const PAGE__CURRENT__PATH = document.location.pathname;
	const PAGE__URL = document.location.origin + document.location.pathname;
	const PAGE__URL__FULL = document.location.href;

	const testimonialForm = document.querySelector(`#testimonialForm`);
	const review_user_name = testimonialForm.querySelector(`input#name`);
	const review_user_email = testimonialForm.querySelector(`input#email`);
	const review_liked = testimonialForm.querySelector(`textarea#liked`);
	const review_disliked = testimonialForm.querySelector(`textarea#not_liked`);

	const widget = document.querySelector(`#testimonial`);
	const widgetHandler = widget.dataset.widgetHandler;
	const widgetSection = widget.dataset.widgetSection;
	const widgetPosition = widget.dataset.widgetPosition;

	dataLayer.push(Object.assign(
			{
				'event': 'addEvents_click',
				'event_id': `d-v1-e1`,
				'event_cat': `w_website`,
				'event_name': `comment`,
				"page_current_path": JSON.stringify(PAGE__CURRENT__PATH),
				"page_group": JSON.stringify(EVENT__CAT),
				"page_url": JSON.stringify(PAGE__URL),
				"page_url_full": JSON.stringify(PAGE__URL__FULL),
				"page_route_id": JSON.stringify(ROUTE__ID),
				"widget_title": JSON.stringify(document.querySelector(`.testimonialWidget__top__title`).innerHTML),
				"widget_id": JSON.stringify(document.querySelector(`div[data-widget-handler="TestimonialWidget"]`).dataset.widgetId),
				"widget_handler": JSON.stringify(widgetHandler),
				"widget_section": JSON.stringify(widgetSection),
				"widget_position": JSON.stringify(widgetPosition)
			},
			{
				'review_user_name': JSON.stringify(`${review_user_name.value}`),
				'review_user_email': JSON.stringify(`${review_user_email.value}`),
				'review_user_rating': JSON.stringify(`${starsWrapper.dataset.value}`),
				'review_liked': JSON.stringify(`${review_liked.value}`),
				'review_disliked': JSON.stringify(`${review_disliked.value}`)
			}, utmParamsTestimonial()
		)
	);
}

const testimonialWidgetDetection = () => {
	let widgetViewed = false;

	const ROUTE = document.body.dataset.routeBonus;
	const ROUTE__ID = document.body.dataset.routeId;
	const ROUTE__EXIST = eventIDTestimonial.findIndex(item => item === ROUTE);
	const EVENT__ID = ROUTE__EXIST > -1 ? ROUTE__EXIST + 1 : eventIDTestimonial.length;
	const EVENT__CAT = ROUTE__EXIST > -1 ? eventIDTestimonial[ROUTE__EXIST] : eventIDTestimonial[eventIDTestimonial.length - 1];

	const PAGE__CURRENT__PATH = document.location.pathname;
	const PAGE__URL = document.location.origin + document.location.pathname;
	const PAGE__URL__FULL = document.location.href;

	const widget = document.querySelector(`#testimonial`);
	const widgetHandler = widget.dataset.widgetHandler;
	const widgetSection = widget.dataset.widgetSection;
	const widgetPosition = widget.dataset.widgetPosition;

	const testimonialWidgetInView = () => {
		if (elementInViewport(widget)) {
			widgetViewed = true;

			dataLayer.push(Object.assign(
				{
					'event': `addEvents_showWidget`,
					'event_id': `d-v1-e61`,
					'event_cat': `w_website`,
					'event_name': `comment`,
					"page_current_path": JSON.stringify(PAGE__CURRENT__PATH),
					"page_url": JSON.stringify(PAGE__URL),
					"page_url_full": JSON.stringify(PAGE__URL__FULL),
					"page_group": JSON.stringify(EVENT__CAT),
					"page_route_id": JSON.stringify(ROUTE__ID),
					"widget_handler": JSON.stringify(widgetHandler),
					"widget_section": JSON.stringify(widgetSection),
					"widget_position": JSON.stringify(widgetPosition)
				},
				utmParamsTestimonial()
			));

			if (window.addEventListener) {
				removeEventListener('DOMContentLoaded', testimonialWidgetInView);
				removeEventListener('load', testimonialWidgetInView);
				removeEventListener('scroll', testimonialWidgetInView);
				removeEventListener('resize', testimonialWidgetInView);
			} else if (window.attachEvent) {
				detachEvent('onDOMContentLoaded', testimonialWidgetInView); // Internet Explorer 9+ :(
				detachEvent('onload', testimonialWidgetInView);
				detachEvent('onscroll', testimonialWidgetInView);
				detachEvent('onresize', testimonialWidgetInView);
			}
		}
	};

	if (window.addEventListener) {
		addEventListener('DOMContentLoaded', testimonialWidgetInView, false);
		addEventListener('load', testimonialWidgetInView, false);
		addEventListener('scroll', testimonialWidgetInView, false);
		addEventListener('resize', testimonialWidgetInView, false);
	} else if (window.attachEvent) {
		attachEvent('onDOMContentLoaded', testimonialWidgetInView); // Internet Explorer 9+ :(
		attachEvent('onload', testimonialWidgetInView);
		attachEvent('onscroll', testimonialWidgetInView);
		attachEvent('onresize', testimonialWidgetInView);
	}
}

const setUpTooltipStyles = (titleTopRating, toolTipDialog) => {
	Array.from(titleTopRating).forEach((c, index) => {
		c.addEventListener('click', () => {
			toolTipDialog[index].style.display === 'block' ?
				toolTipDialog[index].style.display = 'none' :
				toolTipDialog[index].style.display = 'block';
		});
	});
}

document.addEventListener('DOMContentLoaded', () => {
	let titleTopRating = document.getElementsByClassName('testimonialWidget__top__rating');
	let toolTipDialog = document.getElementsByClassName('testimonialWidget__top__rating--tooltip-dialog');

	window.innerWidth <= 768 ? setUpTooltipStyles(titleTopRating, toolTipDialog) : null;

	let testimonialTextarea = Array.from(document.querySelectorAll('.testimonialWidget__form__group textarea'));

	testimonialTextarea.forEach((el) => {
		el.addEventListener('input', () => {
			el.style.height = 'auto';
			el.style.height = el.scrollHeight + 2 + 'px';
		}, false)
	})

	let testimonialDropzoneInput = document.querySelector('.testimonialWidget__form__dropzone input[type="file"]');
	if (testimonialDropzoneInput) {
		let dropzoneElement = testimonialDropzoneInput.closest('.testimonialWidget__form__dropzone');
		let testimonialFormWrapper = document.querySelector('.testimonialWidget__form');

		testimonialWidgetDetection();

		['dragenter', 'dragover', 'dragleave', 'drop'].forEach((evt) => {
			dropzoneElement.addEventListener(evt, (e) => {
				e.preventDefault();
				e.stopPropagation();
			}, false)
		})

		testimonialDropzoneInput.addEventListener('change', (e) => {
			if (testimonialDropzoneInput.files.length) {
				filesManager(dropzoneElement, testimonialDropzoneInput.files)
			}
		})

		dropzoneElement.addEventListener('drop', (e) => {
			manageDrop(dropzoneElement, e);
		}, false);

		dropzoneElement.addEventListener('click', (e) => {
			const {target} = e;
			if (target.closest('.testimonialWidget__form__dropzone__thumb--close')) {
				const currentThumb = target.closest('.testimonialWidget__form__dropzone__thumb');
				const currentThumbIdent = currentThumb.dataset.lastModified;
				const removeIndex = allFiles.findIndex((el) => {
					return el.lastModified === +currentThumbIdent
				})
				allFiles.splice(removeIndex, 1);
				target.closest('.testimonialWidget__form__dropzone__thumb').remove();
			}
		})

		testimonialFormWrapper.addEventListener('click', (e) => {
			const {target} = e;
			const testimonialForm = testimonialFormWrapper.querySelector('form');
			if (target.closest('.testimonialWidget__form__submit')) {
				e.preventDefault();
				if (!validateAllFields(testimonialForm)) {
					return false;
				}
				amplitudeTestimonial();
				submitForm(testimonialForm);
			}
		})
	}
});


const allFiles=[];const headerHeight=document.querySelector(".header").offsetHeight;const filesManager=(dropzoneElement,files)=>{files=[...files];let dropzoneGallery=dropzoneElement.querySelector(".testimonialWidget__form__dropzone__gallery");let dropzoneWrapper=dropzoneElement.querySelector(".testimonialWidget__form__dropzone__wrapper");let dropzoneGalleryAdd=dropzoneElement.querySelector(".testimonialWidget__form__dropzone__add");let dropzoneError=dropzoneElement.querySelector(".testimonialWidget__form__error");if(dropzoneError){dropzoneError.remove()}if(!dropzoneGalleryAdd){let dropzoneWrapperInput=dropzoneWrapper.querySelector('input[type="file"]');let dropzoneGalleryAddImg=document.createElement("div");dropzoneGalleryAddImg.classList.add("testimonialWidget__form__dropzone__add--img");dropzoneGalleryAddImg.innerHTML=`<svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
            <path d="M11 11V5H13V11H19V13H13V19H11V13H5V11H11Z" fill="#5554DE"/>
        </svg>`;dropzoneGalleryAdd=document.createElement("div");dropzoneGalleryAdd.classList.add("testimonialWidget__form__dropzone__add");dropzoneGalleryAdd.appendChild(dropzoneGalleryAddImg);dropzoneGalleryAdd.appendChild(dropzoneWrapperInput);dropzoneWrapper.remove()}if(!dropzoneGallery){dropzoneGallery=document.createElement("div");dropzoneGallery.classList.add("testimonialWidget__form__dropzone__gallery");let dropzoneGalleryTitle=document.createElement("div");dropzoneGalleryTitle.classList.add("testimonialWidget__form__dropzone__gallery--title");dropzoneGalleryTitle.innerHTML="This is never published, but to validate that you are a real player at that casino";dropzoneGallery.appendChild(dropzoneGalleryAdd);dropzoneElement.appendChild(dropzoneGalleryTitle);dropzoneElement.appendChild(dropzoneGallery)}files.forEach(el=>{if(fileValidationExt(el)){allFiles.push(el);previewFile(el,dropzoneGallery)}else{console.log("Your file "+el.name+" has unsupported extension")}})};const fileValidationExt=file=>{const extension=file.name.split(".").pop();const allowedExtensions=["jpg","jpeg","bmp","gif","png","tiff","webp"];return allowedExtensions.includes(extension)};const previewFile=(file,dropzoneGallery)=>{let fileReader=new FileReader;fileReader.readAsDataURL(file);fileReader.onloadend=()=>{let dropzoneThumbItem=document.createElement("div");dropzoneThumbItem.classList.add("testimonialWidget__form__dropzone__thumb");dropzoneThumbItem.dataset.lastModified=file.lastModified;let dropzoneThumbImg=document.createElement("img");dropzoneThumbImg.classList.add("testimonialWidget__form__dropzone__thumb--img");let dropzoneThumbClose=document.createElement("div");dropzoneThumbClose.classList.add("testimonialWidget__form__dropzone__thumb--close");dropzoneThumbImg.src=fileReader.result;dropzoneThumbImg.setAttribute("data-name",file.name);dropzoneThumbClose.innerHTML=`<svg width="10" height="10" viewBox="0 0 10 10" fill="none" xmlns="http://www.w3.org/2000/svg">
                <path d="M4.99981 4.08352L8.20815 0.875183L9.12463 1.79166L5.9163 5L9.12463 8.20833L8.20815 9.12481L4.99981 5.91648L1.79148 9.12481L0.875 8.20833L4.08333 5L0.875 1.79166L1.79148 0.875183L4.99981 4.08352Z" fill="#FF455B"/>
            </svg>`;dropzoneThumbItem.appendChild(dropzoneThumbImg);dropzoneThumbItem.appendChild(dropzoneThumbClose);dropzoneGallery.prepend(dropzoneThumbItem)}};const manageDrop=(dropzoneElement,e)=>{let dataTrans=e.dataTransfer;let files=dataTrans.files;filesManager(dropzoneElement,files)};const validateAllFields=form=>{const name=form.querySelector('input[name="name"]');const nameVal=name.value.trim();const email=form.querySelector('input[name="email"]');const emailVal=email.value.trim();const rating=form.querySelectorAll('input[name="rating"]');const ratingWrapper=form.querySelector(".testimonialWidget__form__radio--wrapper");let ratingVal;rating.forEach(el=>{if(el.checked){ratingVal=el.value}});const liked=form.querySelector('textarea[name="liked"]');const likedVal=liked.value.trim();const notLiked=form.querySelector('textarea[name="not_liked"]');const notLikedVal=notLiked.value.trim();const filesInput=form.querySelector('input[type="file"]');const dropzone=form.querySelector(".testimonialWidget__form__dropzone");const dropzoneWrapper=form.querySelector(".testimonialWidget__form__dropzone__wrapper");const dropzoneGallery=form.querySelector(".testimonialWidget__form__dropzone__gallery");const filesLength=allFiles.length;if(nameVal===""){setError(name,"The name field is required")}else{setSuccess(name)}if(emailVal===""){setError(email,"Email is required")}else if(!isValidEmail(emailVal)){setError(email,"Provide a valid email address")}else{setSuccess(email)}if(!ratingVal||ratingVal===""){setError(ratingWrapper,"Please fill in this input")}else{setSuccess(ratingWrapper)}if(likedVal===""){setError(liked,"Please fill in this input")}else{setSuccess(liked)}if(notLikedVal===""){setError(notLiked,"Please fill in this input")}else{setSuccess(notLiked)}if(filesLength<=0){if(!dropzoneWrapper){setError(dropzoneGallery,"Please fill in this input (.jpg, .jpeg, .gif, .png, .webp)")}else{setError(dropzoneWrapper,"Please fill in this input (.jpg, .jpeg, .gif, .png, .webp)")}}else{setSuccess(dropzone)}return!(nameVal===""||emailVal===""||!isValidEmail(emailVal)||!ratingVal||ratingVal===""||likedVal===""||notLikedVal===""||filesLength<=0)};const setError=(element,message)=>{const inputControl=element;let errorDisplay=element.parentElement.querySelector(".testimonialWidget__form__error");if(!errorDisplay){errorDisplay=document.createElement("div");errorDisplay.classList.add("testimonialWidget__form__error")}errorDisplay.innerText=message;inputControl.parentElement.appendChild(errorDisplay);inputControl.classList.add("invalid");inputControl.classList.remove("success")};const setSuccess=element=>{const inputControl=element;const errorElement=element.parentElement.querySelector(".testimonialWidget__form__error");if(errorElement){errorElement.remove()}const sucesasDisplay=document.createElement("div");sucesasDisplay.classList.add("testimonialWidget__form__success");sucesasDisplay.innerText="";inputControl.classList.add("success");inputControl.classList.remove("invalid")};const isValidEmail=email=>{const re=/^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;return re.test(String(email).toLowerCase())};const submitForm=form=>{const formWrapper=form.closest(".testimonialWidget__form");formWrapper.innerHTML=`<div class="testimonialWidget__form__success">
        <div class="testimonialWidget__form__success--logo">
            <svg width="41" height="40" viewBox="0 0 41 40" fill="none" xmlns="http://www.w3.org/2000/svg">
                <path d="M16.7498 24.9028L32.9987 8.33331L35.5 10.8819L16.7498 30L5.5 18.5295L7.99956 15.9809L16.7498 24.9028Z" fill="#5554DE"/>
            </svg>
        </div>
        <div class="testimonialWidget__form__success--title">Thank you! Your review has been successfully sent</div>
        <div class="testimonialWidget__form__success--description"> Moderation may take up to 24 hours. We will let you know via e-mail when it’s published  </div>
        <button class="testimonialWidget__form__success--btn">Go to bonuses</button>
    </div>`};const setUpTooltipStyles=(titleTopRating,toolTipDialog)=>{Array.from(titleTopRating).forEach((c,index)=>{c.addEventListener("click",()=>{toolTipDialog[index].style.display==="block"?toolTipDialog[index].style.display="none":toolTipDialog[index].style.display="block"})})};document.addEventListener("DOMContentLoaded",()=>{let titleTopRating=document.getElementsByClassName("testimonialWidget__top__rating");let toolTipDialog=document.getElementsByClassName("testimonialWidget__top__rating--tooltip-dialog");window.innerWidth<=768?setUpTooltipStyles(titleTopRating,toolTipDialog):null;let testimonialTextarea=Array.from(document.querySelectorAll(".testimonialWidget__form__group textarea"));testimonialTextarea.forEach(el=>{el.addEventListener("input",()=>{el.style.height="auto";el.style.height=el.scrollHeight+2+"px"},false)});let testimonialDropzoneInput=document.querySelector('.testimonialWidget__form__dropzone input[type="file"]');if(testimonialDropzoneInput){let dropzoneElement=testimonialDropzoneInput.closest(".testimonialWidget__form__dropzone");let testimonialFormWrapper=document.querySelector(".testimonialWidget__form");["dragenter","dragover","dragleave","drop"].forEach(evt=>{dropzoneElement.addEventListener(evt,e=>{e.preventDefault();e.stopPropagation()},false)});testimonialDropzoneInput.addEventListener("change",e=>{if(testimonialDropzoneInput.files.length){filesManager(dropzoneElement,testimonialDropzoneInput.files)}});dropzoneElement.addEventListener("drop",e=>{manageDrop(dropzoneElement,e)},false);dropzoneElement.addEventListener("click",e=>{const{target}=e;if(target.closest(".testimonialWidget__form__dropzone__thumb--close")){const currentThumb=target.closest(".testimonialWidget__form__dropzone__thumb");const currentThumbIdent=currentThumb.dataset.lastModified;const removeIndex=allFiles.findIndex(el=>{return el.lastModified===+currentThumbIdent});allFiles.splice(removeIndex,1);target.closest(".testimonialWidget__form__dropzone__thumb").remove()}});testimonialFormWrapper.addEventListener("click",e=>{const{target}=e;const testimonialForm=testimonialFormWrapper.querySelector("form");if(target.closest(".testimonialWidget__form__submit")){e.preventDefault();if(!validateAllFields(testimonialForm)){return false}submitForm(testimonialForm)}if(target.closest(".testimonialWidget__form__success--btn")){e.preventDefault();const firstH2=document.querySelector("h2");const wrapperH2=firstH2.parentElement;window.scrollTo({behavior:"smooth",top:wrapperH2.offsetTop-headerHeight})}})}});

const userGeo = document.body.dataset.geo;
const domains = [
	'casinosanalyzer.com',
	'kasynoanalyzer.com',
	'ausscasinosanalyzer.com'
];

const getAmplitudeCookieLockWidget = name => {
	let value = `; ${document.cookie}`;
	let parts = value.split(`; ${name}=`);
	if (parts.length === 2) return parts.pop().split(';').shift();
}

const getDevicePlatformLockWidget = () => {
	const ua = navigator.userAgent;
	if (/(tablet|ipad|playbook|silk)|(android(?!.*mobi))/i.test(ua)) {
		return "tablet";
	}
	if (
		/Mobile|iP(hone|od)|Android|BlackBerry|IEMobile|Kindle|Silk-Accelerated|(hpw|web)OS|Opera M(obi|ini)/.test(
			ua
		)
	) {
		return "mob";
	}
	return "web";
};

const appendLockScreen = (title, description) => {
	let div = document.createElement('div');
	div.setAttribute('id', 'lockScreen');

	let options = document.createElement('div');
	let info = document.createElement('div');
	let icon = document.createElement('div');

	div.style.position = 'fixed';
	div.style.top = '0';
	div.style.width = '100%';
	div.style.height = '100vh';
	div.style.background = '#1c3045';
	div.style.color = '#ffffff';
	div.style.zIndex = '999999999999';
	div.style.display = 'flex';
	div.style.alignItems = 'center';
	div.style.justifyContent = 'center';
	div.style.padding = '0 20px';

	info.style.fontSize = '19px';
	info.style.fontWeight = '600';
	info.style.color = '#ffffff';
	info.innerHTML = description;

	icon.style.marginBottom = '10px';
	icon.style.display = 'flex';
	icon.style.alignItems = 'center';
	icon.innerHTML = `
              <svg width="35" height="35"><use href="/build/casinosanalyzer/dist/img/header.svg#logo"></use></svg>
              <span style="font-weight: 600;
                          text-transform: uppercase;
                          letter-spacing: 1px;
                          font-size: 18px;
                          color: #fff;
                          margin-left: 8px;">${title}</span>
      `;

	div.appendChild(options);

	options.appendChild(icon);
	options.appendChild(info);

	document.documentElement.appendChild(div);

	setTimeout(() => {
		document.body.innerHTML = '';
	}, 500);
}

const getDomainName = () => {
	let domain = document.location.host;

	const prefix = [
		'dev.',
		'dev1.',
		'dev2.',
		'dev3.',
		'dev4.',
		'dev5.',
		'qa.',
		'qa2.',
		'qa3.',
		'green.',
		'blue.',
		'preprod.',
	];

	for (let i = 0; i < prefix.length; i++) {
		domain = domain.replace(prefix[i], '');
	}

	return domain;
}

const checkDateIsWeekends = (date = new Date()) => {
	const WEEKENDS_DAYS = {
		'saturday': 6,
		'sunday': 0
	};

	return date.getDay() === WEEKENDS_DAYS['saturday'] || date.getDay() === WEEKENDS_DAYS['sunday'];
}

const geoRestrictions = {
	CH: {
		title: 'Switzerland Casino Analyzer',
		description: 'Due to legal restrictions, our website is not available to visitors using<br/> a Switzerland IP address. We are very sorry for the inconvenience.'
	},
	PL: {
		title: 'Kasyno Analyzer Polska',
		description: 'Niestety nasza strona nie jest dostępna dla odwiedzających, którzy korzystają z polskiego adresu IP. Bardzo przepraszamy<br/> za niedogodności.'
	},
	FR: {
		title: 'FRANCE CASINOS ANALYZER',
		description: 'Due to legal restrictions, our website is not available to visitors using a France IP address. We are very sorry for the inconvenience.'
	},
	NL: {
		title: 'NETHERLANDS CASINOS ANALYZER',
		description: 'Due to legal restrictions, our website is not available to visitors using a Netherlands IP address. We are very sorry for the inconvenience.'
	},
	AU: {
		title: 'AUSTRALIA CASINOS ANALYZER',
		description: 'Access Denied! We are currently unable to accept visitors from Australia. Sorry for the inconvenience!'
	}
};

const enforceGeneralGeoRestrictions = () => {
	const domain = getDomainName();
	const platform = getDevicePlatformLockWidget();
	const isAdmin = getAmplitudeCookieLockWidget('ca_admin');

	if (!domains.includes(domain) || platform !== 'web' || isAdmin || checkDateIsWeekends()) {
		return;
	}

	for (const [key, { title, description }] of Object.entries(geoRestrictions)) {
		if (userGeo === key) {
			appendLockScreen(title, description);
			break;
		}
	}
};

const enforceUaGeoRestriction = () => {
	const restrictedDomainsForUa = domains.concat([
		'casinosanalyzer.ca',
		'casinosanalyzer.co.nz',
		'casinosanalyzer.co.uk'
	]);
	const currentDomain = getDomainName();
	const isAdmin = getAmplitudeCookieLockWidget('ca_admin');

	if (!restrictedDomainsForUa.includes(currentDomain) || isAdmin) {
		return;
	}

	if (userGeo === 'UA') {
		appendLockScreen(
			'Ukraine Casinos Analyzer',
			'Access Denied! We are currently unable to accept visitors from Ukraine. Sorry for the inconvenience!'
		);
	}
};

enforceGeneralGeoRestrictions();
enforceUaGeoRestriction();






import {__translate as oc_widget__translate} from "translate";
import {getLocaleCountry as oc_widget__localcountry} from "globals";

const offlineCasinosMap = document.getElementById('map');

if (offlineCasinosMap) {
	let script = document.createElement('script');
	script.src = 'https://maps.googleapis.com/maps/api/js?key=AIzaSyDyCb81Txuz9-te7c3DvZ2ZuIHIKGvY-cE&callback=initMap';
	script.defer = true;
	window.initMap = function () {
		let map = new google.maps.Map(offlineCasinosMap, {
			center: {lat: +map__lat, lng: +map__lng},
			zoom: +map__zoom,
		});

		LatLngCollection
		.forEach(latlng => {
			let myLatlng = new google.maps.LatLng(+latlng[0], +latlng[1]),
				marker = new google.maps.Marker({
					position: myLatlng,
					title: latlng[2]
				});
			marker.setMap(map);
			marker.addListener("click", toggleBounce);

			function toggleBounce() {
				let hiddenElement = document.querySelector('#' + latlng[3]);

				document.querySelector(`.offline__blocks`).scrollTo({
					top: hiddenElement.offsetTop,
					behavior: "smooth",
				});
			}
		});
	};
	document.head.appendChild(script);

	const offlineShow = document.querySelectorAll(`.offline__show`);
	if (offlineShow.length) {
		offlineShow.forEach(item => {
			let btnText = item.querySelector(`span`);

			item.addEventListener(`click`, () => {
				let textBlock = item.nextElementSibling;

				if (item.classList.contains(`active`)) {
					item.classList.remove(`active`);
					textBlock.classList.remove(`active`);
					btnText.innerHTML = oc_widget__translate('Show More', oc_widget__localcountry()) ?? 'Show More';
				} else {
					item.classList.add(`active`);
					textBlock.classList.add(`active`);
					btnText.innerHTML = oc_widget__translate('Show Less', oc_widget__localcountry()) ?? 'Show Less';
				}
			})
		})
	}
}


import {__translate as __csw_translate} from "translate";

class CasinoCTAWidget {

	/**
	 *
	 * @type {HTMLElement}
	 */
	casinoCtaDescription = document.getElementById('casinoCtaDescription');

	casinoCtaDescriptionParagraph = document.querySelectorAll('#casinoCtaDescription .casino_cta-info-box--more-content');

	/**
	 *
	 * @type {HTMLElement}
	 */
	casinoCtaDescriptionMore = document.getElementById('casinoCtaDescriptionMore');

	onLoadDescriptionShowMore() {
		if (this.casinoCtaDescriptionParagraph.length) {
			this.casinoCtaDescriptionParagraph.forEach(block => {
				let children = [...block.children];
				if (children.length > 1) {
					const showMoreBtn = document.createElement(`span`);
					const LOCALE_COUNTRY = document.querySelector(`body`).dataset.localeCountry.toLowerCase();
					showMoreBtn.innerHTML = __csw_translate("Read more", LOCALE_COUNTRY);
					showMoreBtn.className = `casino_cta-intro-btn`;
					showMoreBtn.addEventListener(`click`, () => {
						children.forEach(item => {
							switch (item.localName) {
								case `table`:
									item.style.display = `table`;
									break;
								case `span`:
								case `a`:
									item.style.display = `inline`;
									break;
								default:
									item.style.display = `block`;
							}
						});
						showMoreBtn.remove();
					})
					children[0].append(showMoreBtn);
				}
			})
		}
	}
}

const casinoCTAWidget = new CasinoCTAWidget;

window.onload = () => {
	casinoCTAWidget.onLoadDescriptionShowMore();
}


const contactForm = document.querySelector(`#contactForm`);
const contactFormSelect = document.querySelector(`#contactFormSelect`);
const contactFormSelectValue = document.querySelector(`#contactFormSelectValue`);
const contactFormSelectItems = document.querySelectorAll(`#contactFormSelectItems li`);

if (contactForm) {
	contactFormSelect.addEventListener(`click`, e => {
		e.stopPropagation();
		contactFormSelect.classList.toggle(`active`);
	});

	contactFormSelectItems.forEach(item => {
		item.addEventListener(`click`, () => {
			let activeItem = document.querySelector(`#contactFormSelectItems li.active`);
			activeItem && activeItem.classList.remove(`active`);

			item.classList.add(`active`);
			contactFormSelectValue.innerHTML = item.innerHTML;
			contactFormSelectValue.dataset.name = item.innerHTML;
		});
	})

	document.addEventListener(`click`, () => {
		contactFormSelect.classList.contains(`active`) && contactFormSelect.classList.remove(`active`);
	})

	const submitFormPopup = () => {
		const contactFormPopup = document.querySelector(`#contactFormPopup`),
			contactFormPopupClose = contactFormPopup.querySelectorAll(`button`);

		contactFormPopup.classList.add(`show`);
		document.body.classList.add(`overflow-hidden`);

		contactFormPopupClose.forEach(btn => {
			btn.addEventListener(`click`, () => {
				location.reload();
			});
		})
	}

	contactForm.addEventListener(`submit`, e => {
		e.preventDefault();

		let errorDetected = false;

		const type = document.querySelector(`.contactForm_type`),
			name = document.querySelector(`.contactForm_name`),
			email = document.querySelector(`.contactForm_email`),
			message = document.querySelector(`.contactForm_message`);

		type.classList.remove(`error`);
		name.classList.remove(`error`);
		email.classList.remove(`error`);
		message.classList.remove(`error`);

		if (!contactFormSelectValue.dataset.name) {
			type.classList.add(`error`);
			errorDetected = true;
		}

		if (!name.querySelector(`input`).value) {
			name.classList.add(`error`);
			errorDetected = true;
		}

		if (!email.querySelector(`input`).value) {
			email.classList.add(`error`);
			errorDetected = true;
		}

		if (!message.querySelector(`textarea`).value) {
			message.classList.add(`error`);
			errorDetected = true;
		}

		let grecaptcha = document.querySelector(`#grecaptcha`);

		if (grecaptcha) {
			let response = grecaptcha.getResponse();
			if (response.length == 0) return;

		}

		!errorDetected && submitFormPopup();
	})
}


const topSlotsSelector = document.querySelector('.topSlotsWidget');
const topSlotsCardsWrapper = topSlotsSelector.querySelector('.topSlotsWidget__cards');

const topSlotsCards = Array.from(topSlotsSelector.querySelectorAll('.topSlotsWidget__card__wrapper'));
const topSlotsCardsContent = Array.from(topSlotsSelector.querySelectorAll('.topSlotsWidget__main'));
topSlotsCards.forEach((el, ind) => {
	el.addEventListener('click', e => {
		const {target} = e

		if (target.closest('.topSlotsWidget__table__more')) {
			removeAllDropdowns([...topSlotsCards]);
			if (window.innerWidth >= 768) {
				topSlotCardsEqualItemsHeight(topSlotsCardsContent);
				el.closest('.topSlotsWidget__cards').classList.add('flex-row');
			}
			el.classList.add('dropdown-show');
		}
	})
})

const removeAllDropdowns = (items) => {
	items.forEach((el) => {
		if (el.classList.contains('dropdown-show')) {
			el.classList.remove('dropdown-show')
			topSlotsCardsWrapper.classList.remove('flex-row');
		}
	})
}

const topSlotCardsEqualItemsHeight = (items) => {
	const highest = Math.max(...items.map(item => item.offsetHeight))
	items.forEach((el) => {
		el.style.minHeight = highest + 'px';
	})
}

const showHidePlayBtn = (desktopWidth) => {
	if (window.innerWidth >= desktopWidth) {

		topSlotsCards.forEach(el => {

			const imgWrapper = el.querySelector('.topSlotsWidget__card__img-wrapper');
			const playBtn = el.querySelector('.topSlotsWidget__play');

			el.addEventListener('mouseenter', e => {
				playBtn.classList.add('show');
				const imgWrapperHeight = imgWrapper.offsetHeight;
				const playBtnHeight = playBtn.offsetHeight;
				const playBtnPos = imgWrapperHeight / 2 - playBtnHeight / 2;
				playBtn.style.top = playBtnPos + 'px';
			})

			el.addEventListener('mouseleave', e => {
				playBtn.classList.remove('show');
			})
		})
	}
}

showHidePlayBtn(1200);


import WorldMap from "WorldMapMarkers";

document.addEventListener('DOMContentLoaded', () => {
	const casinoVisitsMap = new WorldMap();
	casinoVisitsMap.generateCasinoVisitsWidgetMap();
})


class TableOfContentWidget {

	allTbocWidgets = Array.from(document.querySelectorAll('.tableOfContentWidget'));
	header = document.querySelector('.header');


	initTbocWIdget() {
		if (this.allTbocWidgets.length > 0) {
			this.allTbocWidgets.forEach(widget => {
				this.clickTbocWidget(widget)
			})
		}
	}

	clickTbocWidget(widget) {
		widget.addEventListener('click', (e) => {
			const {target} = e;
			if (target.closest('.tableOfContentWidget__arrow')) {
				this.toggleTboc(widget)
			}
			if (target.closest('.tableOfContentWidget__link')) {
				e.preventDefault();
				this.scrollToTarget(target)
			}
		})
	}

	toggleTboc(widget) {
		if (widget.classList.contains('show')) {
			widget.classList.remove('show')
		} else {
			widget.classList.add('show')
		}
	}

	scrollToTarget(item) {
		const itemTarget = decodeURIComponent(item.hash);

		if (itemTarget) {
			const scrollTarget = document.querySelector(itemTarget);

			if (scrollTarget) {
				return window.scrollTo({
					top: scrollTarget.getBoundingClientRect().top + window.scrollY - this.header.offsetHeight,
					left: 0,
					behavior: 'smooth'
				});
			}
		}

		return console.warn(`Target element "${itemTarget}" not found.`);
	}
}

document.addEventListener('DOMContentLoaded', () => {
	const tableOfContentWidget = new TableOfContentWidget();
	tableOfContentWidget.initTbocWIdget();
})


import {navAff as navAffSearchForm, utmParams as utmParamsSearch, eventID as eventIDSearch} from "globals";
import {geoCloudflareLocation as geoCloudflareLocationSearchForm} from "api";
import {__translate as __sw_translate} from "translate";
import {centrifugeManager as searchWidgetCentrifugeManager} from 'CentrifugeManager';

const SEARCH_FORM_VER = '1.0';

const searchFormFuncSearchForm = () => {
    const searchFormInput = document.querySelector(`.frontSearch__form #form_domain`);
    const searchFormBtn = document.querySelector(`.frontSearch__form #form_save`);

    const headerSearchFront = document.querySelector(`.frontSearch`);
    const headerSearchForm = document.querySelector(`.frontSearch__form form`);

    const primeBlock = document.querySelector(`.prime-bg`);

    const frontSearchBtnClose = document.querySelector(`.frontSearch__btn--close`);

    const frontSearchFormBtn = document.querySelector(`.frontSearch__form__btn`);

    const LOCALE_COUNTRY = document.querySelector(`body`).dataset.localeCountry.toLowerCase();
    const COUNTRY_NAME = (searchDropdownSearchForm.dataset.country === `Poland` || searchDropdownSearchForm.dataset.country === 'Polska') ? `Polsce` : searchDropdownSearchForm.dataset.country;

    const getLoc = async () => {
        let loc = document.body.dataset.geo;
        if (!loc) loc = await geoCloudflareLocationSearchForm();

        storage.setGeo(loc);

        return loc;
    }

    const getOffers = async (limit = 6) => {
        let displaySponsoredPosition = 'false';
        let sponsoredFrequency = 0;
        let sponsoredStartPosition = 0;
        let loc = await getLoc();

        headerSearchFront.dataset.sponsoredFrequency ? sponsoredFrequency = headerSearchFront.dataset.sponsoredFrequency : sponsoredFrequency;
        headerSearchFront.dataset.sponsoredStartPosition ? sponsoredStartPosition = headerSearchFront.dataset.sponsoredStartPosition : sponsoredStartPosition;
        headerSearchFront.dataset.sponsoredDisplay ? displaySponsoredPosition = headerSearchFront.dataset.sponsoredDisplay : displaySponsoredPosition;

        let searchFormPopular = storage.getSearchFormPopular();
        if (!searchFormPopular) {
            let endpointByOutputType = `/api/offers?country=${loc}&limit=${limit}&sort=true`;

            if (displaySponsoredPosition === 'true') {
                endpointByOutputType += `&sponsored=true`;

                if (sponsoredFrequency) {
                    endpointByOutputType += `&sponsored_frequency=${sponsoredFrequency}`
                }

                if (sponsoredStartPosition) {
                    endpointByOutputType += `&sponsored_start_position=${sponsoredStartPosition}`
                }
            }

            searchFormPopular = await fetch(endpointByOutputType, {mode: "cors"})
                .then(res => res.json())
                .then(data => {
                    storage.setSearchFormPopular(data);
                    return data;
                });
        } else {
            searchFormPopular = storage.getSearchFormPopular();
        }

        return searchFormPopular;
    }

    const getSlots = async (limit = 5) => {
        let loc = await getLoc();

        let searchFormSlots = storage.getSearchFormSlots();

        if (!searchFormSlots) {
            searchFormSlots = await fetch(`/api/slots?country=${loc}&limit=${limit}`, {mode: "cors"})
                .then(res => res.json())
                .then(data => data.map(item => {
                    return item;
                }))
                .then(data => {
                    storage.setSearchFormSlots(data);
                    return data;
                })
        } else
            searchFormSlots = storage.getSearchFormSlots();

        return searchFormSlots;
    }

    const SEARCH_COUNT_ALL = 9;
    const SEARCH_COUNT = 5;

    const getSearch = async (value, type = `all`) => await fetch(`/search-hint?search=${value}&limit=${type === `all` ? SEARCH_COUNT_ALL : SEARCH_COUNT}&type=${type}`)
        .then(data => data.json());

    let renderedSearchDropdown = false;

    if (searchFormInput) {
        searchFormInput.setAttribute(`autocomplete`, `off`);

        searchFormInput.addEventListener(`click`, e => {
            e.stopPropagation();
        });

        searchFormInput.addEventListener(`focus`, e => {
            e.stopPropagation();
            showSearchDropdown();
        });

        let debounceTimer;
        let lastInputValue = '';

        searchFormInput.addEventListener(`input`, e => {
            e.stopPropagation();
            const inputValue = e.target.value;

            clearTimeout(debounceTimer);

            if (inputValue !== lastInputValue) {
                lastInputValue = inputValue;

                debounceTimer = setTimeout(() => {
                    renderSearchResult(inputValue).then(r => r);
                }, 1000);
            }
        });

        searchFormBtn.addEventListener(`click`, e => {
            e.stopPropagation();
            showSearchDropdown();

            let searchResult = document.querySelector(`.search__result--container .item`);
            searchResult && !headerSearchForm ? searchResult.click() : showSearchDropdown();
        });

        headerSearchForm && headerSearchForm.addEventListener(`submit`, e => {
            e.preventDefault();
            let searchResult = document.querySelector(`.search__result--container .item`);
            searchResult && searchResult.click();
        });

        searchDropdownSearchForm.addEventListener(`click`, e => {
            e.stopPropagation();
        });
    }

    document.body.addEventListener(`click`, () => {
        if (document.body.classList.contains(`searchDropdown`)) {
            document.body.classList.remove(`searchDropdown`);
        }
    })

    const renderSearchResult = async (value) => {
        if (value.length) {
            const searchContainer = document.querySelector(`.search__result--container`);

            let type = document.querySelector(`.search__btns--items button.active`).dataset.name;
            let result = await getSearch(value, type);

            searchContainer.innerHTML = ``;

            let casinos = result.filter(item => item.group === `casino`),
                bonuses = result.filter(item => item.group === `bonus`),
                slots = result.filter(item => item.group === `slot`);

            switch (type) {
                case `all`:
                    searchContainer.append(
                        casinos.length ? await renderSearchReviews(casinos, 3) : ``,
                        bonuses.length ? await renderSearchBonuses(bonuses, 3) : ``,
                        slots.length ? await renderSearchSlots(slots, 3) : ``);
                    break;
                case `casino`:
                    casinos.length && searchContainer.append(await renderSearchReviews(casinos, 5));
                    break;
                case `bonus`:
                    bonuses.length && searchContainer.append(await renderSearchBonuses(bonuses, 5));
                    break;
                case `slot`:
                    slots.length && searchContainer.append(await renderSearchSlots(slots, 5));
                    break;
            }
        }
    }

    frontSearchFormBtn && frontSearchFormBtn.addEventListener(`click`, e => {
        e.stopPropagation();

        let searchResult = document.querySelector(`.search__result--container .item`);
        searchResult ? searchResult.click() : showSearchDropdown();
    })

    frontSearchBtnClose && frontSearchBtnClose.addEventListener(`click`, e => {
        e.stopPropagation();
        headerSearchFront.classList.remove(`show`);
        frontSearchBtnClose.classList.remove(`active`);
        if (primeBlock) primeBlock.style.overflow = `hidden`;
    })

    document.body.addEventListener(`click`, e => {
        if (headerSearchFront && headerSearchFront.classList.contains(`show`)) {
            headerSearchFront.classList.remove(`show`);
            frontSearchBtnClose.classList.remove(`active`);
            if (primeBlock) primeBlock.style.overflow = `hidden`;
        }
    })

    const showSearchDropdown = () => {
        if (!renderedSearchDropdown) renderSearchDropdown();
        headerSearchFront.classList.add(`show`);
        frontSearchBtnClose.classList.add(`active`);
        if (primeBlock) primeBlock.style.overflow = `inherit`;
    }

    const renderSearchDropdown = async () => {
        renderedSearchDropdown = true;

        const popularContainer = renderSearchPopularContainer();
        popularContainer.append(await renderSearchPopular(), renderSearchNav());

        const scrollContainer = document.createElement(`div`);
        scrollContainer.className = `search__scroll--container`;
        scrollContainer.append(renderSearchContainer(), popularContainer);

        searchDropdownSearchForm.append(renderSearchBtns(), scrollContainer);
        handleSearchBtns();
    }

    const renderSearchContainer = () => {
        let div = document.createElement(`div`);
        div.className = `search__result--container`;
        return div;
    }

    const handleSearchBtns = () => {
        const btns = document.querySelectorAll(`.search__btns--items button`);
        const popularContainer = document.querySelector(`.search__popular--container`);
        btns.forEach(btn => {
            btn.addEventListener(`click`, async e => {
                e.stopPropagation();

                popularContainer.innerHTML = ``;
                document.querySelector(`.search__btns--items button.active`).classList.remove(`active`);
                btn.classList.add(`active`);

                switch (btn.dataset.name) {
                    case `all`:
                        popularContainer.append(await renderSearchPopular(), renderSearchNav());
                        break;
                    case `casino`:
                        popularContainer.append(await renderSearchPopularCasinos());
                        break;
                    case `bonus`:
                        popularContainer.append(await renderSearchPopularBonuses());
                        break;
                    case `slot`:
                        if (await renderSearchPopularSlots() !== null) {
                            popularContainer.append(await renderSearchPopular(), await renderSearchPopularSlots());
                        } else {
                            popularContainer.append(await renderSearchPopular());
                        }
                        break;
                }

                renderSearchResult(searchFormInput.value);
            })
        })
    }

    const renderSearchBtns = () => {
        const casinoPath = searchDropdownSearchForm.dataset.casino;
        const bonusPath = searchDropdownSearchForm.dataset.bonus;
        const slotPath = searchDropdownSearchForm.dataset.slot;

        const block = document.createElement(`div`);
        block.className = `search__btns`;
        block.innerHTML = `<div class="search__btns--items">
	      <button type="button" data-name="all" class="active">${__sw_translate("All", LOCALE_COUNTRY)}</button>
	      ${casinoPath && `<button type="button" data-name="casino">${__sw_translate("Casino Reviews", LOCALE_COUNTRY)}</button>`}
	      ${bonusPath && `<button type="button" data-name="bonus">${__sw_translate("Bonuses", LOCALE_COUNTRY)}</button>`}
	      ${slotPath && `<button type="button" data-name="slot">${__sw_translate("Slots", LOCALE_COUNTRY)}</button>`}
	  </div>`;

        return block;
    }

    const renderSearchNav = () => {
        const casinoPath = searchDropdownSearchForm.dataset.casino;
        const bonusPath = searchDropdownSearchForm.dataset.bonus;
        const slotPath = searchDropdownSearchForm.dataset.slot;

        const domainName = document.location.host
            .replace(`loc.`, ``)
            .replace(`dev.`, ``)
            .replace(`green.`, ``)
            .replace(`blue.`, ``);

        let data = [];

        if (domainName === `casinosanalyzer.com`) data.push({
            text: __sw_translate("Free spins no deposit", LOCALE_COUNTRY),
            path: `free-spins-no-deposit`
        });


        if (bonusPath) data.push({
            text: __sw_translate("Casino bonuses", LOCALE_COUNTRY),
            path: bonusPath
        });

        if (domainName === `casinosanalyzer.com`) data.push({
            text: __sw_translate("New bonuses", LOCALE_COUNTRY),
            path: `free-spins-no-deposit/new`
        });

        if (casinoPath) data.push({
            text: __sw_translate("Online casinos", LOCALE_COUNTRY),
            path: casinoPath
        });

        if (slotPath) data.push({
            text: __sw_translate("Free slots", LOCALE_COUNTRY),
            path: slotPath
        });

        const block = document.createElement(`div`);
        block.className = `search__nav`;
        block.innerHTML = data
            .map(item => `<a href="/${item.path}">
      <img src="/build/casinosanalyzer/img/redesign/search.svg" alt="search">
      <span>${item.text}</span>
  </a>`)
            .join(``);

        return block;
    }

    const renderSearchPopularContainer = () => {
        const block = document.createElement(`div`);
        block.className = `search__popular--container`;
        return block;
    }

// amplitudeDataset
    const amplitudeDataset = (block, item, index) => {
        block.dataset.score = JSON.stringify(item.score ? item.score : item.rate ? item.rate : 4);
        block.dataset.titleShort = JSON.stringify(item.titleShort ? item.titleShort : null);
        block.dataset.titleLong = JSON.stringify(item.titleLong ? item.titleLong : null);
        block.dataset.affiliateUrl = JSON.stringify(item.affiliateUrl ? item.affiliateUrl : null);
        block.dataset.id = JSON.stringify(item.id ? item.id : null);
        block.dataset.amountMax = JSON.stringify(item.amountMax ? item.amountMax : 0);
        block.dataset.percent = JSON.stringify(item.percent ? item.percent : 0);
        block.dataset.expired = JSON.stringify(item.expiredDate ? item.expiredDate : null);
        block.dataset.specialButtonTitle = JSON.stringify(item.specialButtonTitle ? item.specialButtonTitle : null);
        block.dataset.wageringRequirements = JSON.stringify(item.wageringRequirements ? item.wageringRequirements : 0);
        block.dataset.depositMin = JSON.stringify(item.depositMinValue);
        block.dataset.code = JSON.stringify(item.code ? item.code : null);
        block.dataset.label = JSON.stringify(item.label ? item.label : null);
        block.dataset.bonusCategories = JSON.stringify(item.bonusCategories ? item.bonusCategories : null);
        block.dataset.bonusTypes = JSON.stringify(item.bonusTypes ? item.bonusTypes : null);
        block.dataset.freeSpins = JSON.stringify(item.freeSpins ? item.freeSpins : 0);
        block.dataset.widget_list_index = JSON.stringify(index);
        block.dataset.currency = JSON.stringify(item.currency && Array.isArray(item.currency) && item.currency.length && !(item.currency).every(item => item === null) ? item.currency : ["Not Set"]);
        block.dataset.slots = JSON.stringify(item.slots && Array.isArray(item.slots) && item.slots.length ? item.slots.map(item => item.name) : ["Not Set"]);
        block.dataset.casino_bonus_category_display = JSON.stringify(null);
        block.dataset.casino_geo_rating = JSON.stringify(item.score ? +item.score.toFixed(1) : 0);
        block.dataset.casino_bonus_exclusive = JSON.stringify(item.exclusive ? item.exclusive : false);
        block.dataset.casino_bonus_code = JSON.stringify(item.code ? item.code : "Not Set");
        block.dataset.casino_bonus_cashable = JSON.stringify(item.cashable ? item.cashable : false);

        if (item.casino) {
            block.dataset.casinoId = JSON.stringify(item.casino.casinoId);
            block.dataset.name = JSON.stringify(item.casino.name);
            block.dataset.domain = JSON.stringify(item.casino.domain);
        } else {
            block.dataset.casinoId = JSON.stringify(null);
            block.dataset.name = JSON.stringify(item.name ? item.name : null);
            block.dataset.domain = JSON.stringify(item.domain ? item.domain : item.slug ? item.slug : null);
        }

        let casino_bonus_days_after_create = 0;
        if (item.created) {
            const createdDate = new Date(item.created.date);
            const currentDate = new Date();
            const diffTime = Math.abs(currentDate - createdDate);
            casino_bonus_days_after_create = Math.floor(diffTime / (1000 * 60 * 60 * 24));
        }
        block.dataset.casino_bonus_days_after_create = JSON.stringify(+casino_bonus_days_after_create);

        let casino_bonus_active_days_left = 365;
        if (item.expiredDate) {
            const expiredDate = new Date(item.expiredDate.date);
            const currentDate = new Date();
            if (expiredDate < currentDate) casino_bonus_active_days_left = 0;
            else {
                const diffTime = Math.abs(expiredDate - currentDate);
                casino_bonus_active_days_left = Math.floor(diffTime / (1000 * 60 * 60 * 24)) + 1;
            }
        }
        block.dataset.casino_bonus_active_days_left = JSON.stringify(+casino_bonus_active_days_left);
        block.dataset.sponsored = JSON.stringify(item.sponsored ? true : false);

        return block;
    }
// amplitudeDataset

// popular
    const renderSearchPopular = async () => {
        let data = await getOffers(6);
        let items = data
            .slice(0, 5)
            .map((item, index) => {
                let rating = [];
                for (let i = 1; i <= 5; i++) {
                    rating.push(`<img src="/build/casinosanalyzer/img/redesign/${i <= Math.round(item.sponsored ? 5 : item.score) ? `star-full` : `star`}.svg" alt="star">`);
                }

                let block = document.createElement(`div`);
                block.className = `item`;
                block = amplitudeDataset(block, item, ++index);

                block.innerHTML = `<div class="item__logo ${item.sponsored ? 'item__logo--sponsored' : ''}">
                    <div class="item__logo--wrapper" style="background-color: #${item.casino?.background ? item.casino.background : 'fff'}">
                        ${item.sponsored ? `<div class="item__logo--timer"><svg>
                <use href="/build/midori/assets/icons/icons.svg#stopwatch"></use>
            </svg>Limited</div>` : ``}
                         <img src="${item.casino?.logo ? item.casino.logo : 'fff'}" alt="${item.casino.name}">
                    </div>
      </div>
      <div class="item__rating">
          ${rating.join(``)}
      </div>
      <p class="item__title">${item.casino.name}</p>`;

                block.addEventListener(`click`, e => {
                    e.stopPropagation();
                    navAffSearchForm(`${item.casino.domain}?bonus=${item.id}`, true, {}, false, item.affiliateUrl);
                    searchWidgetCentrifugeManager.publishCustomEvent('bonusClicked', {
                        bonusId: item.id,
                        isSponsored: item.sponsored
                    });
                    searchAmplitudeClick(block);
                })

                return block;
            });

        const block = document.createElement(`div`);

        block.className = `search__popular`;
        block.innerHTML = headerSearchFront.dataset.sponsoredDisplay === 'true' ? `<p>${__sw_translate("Sponsored offers", LOCALE_COUNTRY)}</p>` : `<p>${__sw_translate("Popular search results in", LOCALE_COUNTRY)} <span>${COUNTRY_NAME}</span></p>`;

        let blockItems = document.createElement(`div`);
        blockItems.className = `search__popular--items`;
        items.forEach(item => blockItems.append(item));

        block.append(blockItems);

        return block;
    }

    const renderSearchPopularCasinos = async () => {
        let data = await getOffers(5);
        const casinoPath = searchDropdownSearchForm.dataset.casino;
        let items = data
            .slice(0, 4)
            .map((item, index) => {
                let block = document.createElement(`div`);
                block.className = `item`;
                block = amplitudeDataset(block, item, ++index);

                block.innerHTML = `<div class="item__logo" style="background-color: #${item.casino.background}">
            <img src="${item.casino.logo}" alt="${item.casino.name}">
        </div>
				<div class="item__info">
					<p class="item__title">
						<span>${item.casino.name}</span>
						<img src="/build/casinosanalyzer/img/redesign/star-full.svg" alt="star">
	          ${item.score.toFixed(1)}
					</p>
					<p class="item__subtitle">${__sw_translate("In Casino reviews", LOCALE_COUNTRY)}</p>
        </div>`;

                block.addEventListener(`click`, e => {
                    e.stopPropagation();
                    document.location.href = `/${casinoPath}/${item.casino.domain}`
                    searchAmplitudeClick(block);
                })

                return block;
            });

        const block = document.createElement(`div`);
        block.className = `search__popular search__popular--casinos`;
        block.innerHTML = `<p>${__sw_translate("Popular Casino Reviews in", LOCALE_COUNTRY)} <span>${COUNTRY_NAME}</span></p>`;

        let blockItems = document.createElement(`div`);
        blockItems.className = `search__popular--items`;
        items.forEach(item => blockItems.append(item));

        block.append(blockItems);

        return block;
    }

    const renderSearchPopularBonuses = async () => {
        let data = await getOffers(5);
        let items = data
            .slice(0, 4)
            .map((item, index) => {
                let block = document.createElement(`div`);
                block.className = `item`;
                block = amplitudeDataset(block, item, ++index);

                block.innerHTML = `<div class="item__logo ${item.sponsored ? 'sponsored' : ''}" style="background-color: #${item.casino.background}">
            <img src="${item.casino.logo}" alt="${item.casino.name}">
        </div>
				<div class="item__info">
					<p class="item__title">
						<span>${item.title}</span>
						<img src="/build/casinosanalyzer/img/redesign/star-full.svg" alt="star">
	          ${item.score.toFixed(1)}
					</p>
					<p class="item__subtitle">${__sw_translate("In Bonuses", LOCALE_COUNTRY)}</p>
        </div>`;

                block.addEventListener(`click`, e => {
                    e.stopPropagation();
                    navAffSearchForm(`${item.casino.domain}?bonus=${item.id}`, true, {}, false, item.affiliateUrl);
                    searchWidgetCentrifugeManager.publishCustomEvent('bonusClicked', {
                        bonusId: item.id,
                        isSponsored: item.sponsored
                    });
                    searchAmplitudeClick(block);
                })

                return block;
            });

        const block = document.createElement(`div`);
        block.className = `search__popular search__popular--bonuses`;
        block.innerHTML = headerSearchFront.dataset.sponsoredDisplay === 'true' ? `<p>${__sw_translate("Sponsored offers", LOCALE_COUNTRY)}</p>` : `<p>${__sw_translate("Popular Bonuses in", LOCALE_COUNTRY)} <span>${COUNTRY_NAME}</span></p>`;

        let blockItems = document.createElement(`div`);
        blockItems.className = `search__popular--items`;
        items.forEach(item => blockItems.append(item));

        block.append(blockItems);

        return block;
    }

    const renderSearchPopularSlots = async () => {
        const RANK_DEFAULT = 4;
        const slotPath = searchDropdownSearchForm.dataset.slot;
        let data = await getSlots(5);

        if (data.length > 0) {
            let items = data
                .slice(0, 4)
                .map((item, index) => {
                    let block = document.createElement(`div`);
                    block.className = `item`;
                    block = amplitudeDataset(block, item, ++index);

                    block.innerHTML = `<div class="item__info">
					<p class="item__title">
						<span>${item.name}</span>
						<img src="/build/casinosanalyzer/img/redesign/star-full.svg" alt="star">
	          ${item.rank ? item.rank.toFixed(1) : RANK_DEFAULT.toFixed(1)}
					</p>
					<p class="item__subtitle">${__sw_translate("In Slots", LOCALE_COUNTRY)}</p>
        </div>`;

                    block.addEventListener(`click`, e => {
                        e.stopPropagation();
                        document.location.href = `/${slotPath}/${item.slug}`;
                        searchAmplitudeClick(block);
                    });

                    return block;
                });

            const block = document.createElement(`div`);
            block.className = `search__popular search__popular--slots`;
            block.innerHTML = `<p>${__sw_translate("Popular Slots in", LOCALE_COUNTRY)} <span>${COUNTRY_NAME}</span></p>`;

            let blockItems = document.createElement(`div`);
            blockItems.className = `search__popular--items`;
            items.forEach(item => blockItems.append(item));

            block.append(blockItems);

            return block;
        }
        return null;
    }
// popular

// search result
    const renderSearchReviews = async (data, limit) => {
        const SCORE_DEFAULT = 4;
        const SCORE_MAX = 5;
        let items = data
            .slice(0, limit)
            .map((item, index) => {
                let block = document.createElement(`div`);
                block.className = `item`;
                block = amplitudeDataset(block, item, ++index);

                block.innerHTML = `<div class="item__logo" style="background-color: #${item.background}">
            <img src="${item.logo}" alt="${item.name}">
        </div>
				<div class="item__info">
					<p class="item__title">
						<span>${item.name}</span>
						<img src="/build/casinosanalyzer/img/redesign/star-full.svg" alt="star">
	          ${item.score ? (item.score > SCORE_MAX ? SCORE_DEFAULT.toFixed(1) : item.score.toFixed(1)) : SCORE_DEFAULT.toFixed(1)}
					</p>
					<p class="item__subtitle">${__sw_translate("In Casino reviews", LOCALE_COUNTRY)}</p>
        </div>`;

                block.addEventListener(`click`, e => {
                    e.stopPropagation();
                    document.location.href = item.path;
                    searchAmplitudeClick(block);
                })

                return block;
            });

        const block = document.createElement(`div`);
        block.className = `search__popular search__popular--casinos`;
        block.innerHTML = `<p>${__sw_translate("Found in", LOCALE_COUNTRY)} ${__sw_translate("Casino Reviews", LOCALE_COUNTRY)}</p>`;

        let blockItems = document.createElement(`div`);
        blockItems.className = `search__popular--items`;
        items.forEach(item => blockItems.append(item));

        block.append(blockItems);

        return block;
    }

    const renderSearchBonuses = async (data, limit) => {
        let items = data
            .slice(0, limit)
            .map((item, index) => {
                let block = document.createElement(`div`);
                block.className = `item`;
                block = amplitudeDataset(block, item, ++index);

                block.innerHTML = `<div class="item__logo" style="background-color: #${item.background}">
            <img src="${item.logo}" alt="${item.name}">
        </div>
				<div class="item__info">
					<p class="item__title">
						<span>${item.alias}</span>
						<img src="/build/casinosanalyzer/img/redesign/star-full.svg" alt="star">
	          ${item.score.toFixed(1)}
					</p>
					<p class="item__subtitle">${__sw_translate("In Bonuses", LOCALE_COUNTRY)}</p>
        </div>`;

                block.addEventListener(`click`, e => {
                    e.stopPropagation();
                    document.location.href = item.path;
                    searchAmplitudeClick(block);
                })

                return block;
            });

        const block = document.createElement(`div`);
        block.className = `search__popular search__popular--bonuses`;
        block.innerHTML = `<p>${__sw_translate("Found in Bonuses", LOCALE_COUNTRY)}</p>`;

        let blockItems = document.createElement(`div`);
        blockItems.className = `search__popular--items`;
        items.forEach(item => blockItems.append(item));

        block.append(blockItems);

        return block;
    }

    const renderSearchSlots = async (data, limit) => {
        const RANK_DEFAULT = 4;
        const RANK_MAX = 4;
        let items = data
            .slice(0, limit)
            .map((item, index) => {
                let block = document.createElement(`div`);
                block.className = `item`;
                block = amplitudeDataset(block, item, ++index);

                block.innerHTML = `<div class="item__info">
					<p class="item__title">
						<span>${item.name}</span>
						<img src="/build/casinosanalyzer/img/redesign/star-full.svg" alt="star">
	          ${item.rank ? (item.rank > RANK_MAX ? RANK_DEFAULT.toFixed(1) : item.rank.toFixed(1)) : RANK_DEFAULT.toFixed(1)}
					</p>
					<p class="item__subtitle">${__sw_translate("In Slots", LOCALE_COUNTRY)}</p>
        </div>`;

                block.addEventListener(`click`, e => {
                    e.stopPropagation();
                    document.location.href = item.path;
                    searchAmplitudeClick(block);
                });

                return block;
            });

        const block = document.createElement(`div`);
        block.className = `search__popular search__popular--slots`;
        block.innerHTML = `<p>${__sw_translate("Found in Slots", LOCALE_COUNTRY)}</p>`;

        let blockItems = document.createElement(`div`);
        blockItems.className = `search__popular--items`;
        items.forEach(item => blockItems.append(item));

        block.append(blockItems);

        return block;
    }
// search result

    window.addEventListener('pagehide', () => {
        storage.getSearchFormPopular() ? storage.removeSearchFormPopular() : null;
    });
}

// searchAmplitudeClick
let searchAffLinkClickIndex = 0;
const searchAmplitudeClick = item => {
    const searchForm = document.querySelector('#form_domain');
    const headerSearch = document.querySelector(`.header__search`);
    const container = headerSearch ? headerSearch : searchForm.closest(`.container-fluid`);
    const widgetId = container.dataset.widgetId;
    const widgetHandler = container.dataset.widgetHandler;
    const widgetPosition = container.dataset.widgetPosition;

    const casinoScoreGeoText = (value) => {
        let casino_score_geo_text = "";
        if (value === 5) {
            casino_score_geo_text = "A";
        } else if (value > 4.5 && value <= 4.9) {
            casino_score_geo_text = "B";
        } else if (value > 4 && value <= 4.5) {
            casino_score_geo_text = "C";
        } else if (value <= 4) {
            casino_score_geo_text = "D";
        }
        return casino_score_geo_text;
    };

    const PAGE__CURRENT__PATH = document.location.pathname,
        PAGE__URL = document.location.origin + document.location.pathname,
        PAGE__URL__FULL = document.location.href,
        ROUTE = document.body.dataset.routeBonus,
        ROUTE__ID = document.body.dataset.routeId,
        ROUTE__EXIST = eventIDSearch.findIndex(item => item === ROUTE),
        EVENT__ID = ROUTE__EXIST > -1 ? ROUTE__EXIST + 1 : eventIDSearch.length,
        EVENT__CAT = ROUTE__EXIST > -1 ? eventIDSearch[ROUTE__EXIST] : eventIDSearch[eventIDSearch.length - 1],
        LOCALE__LANG = document.body.dataset.localeLang,
        WEBSITE__ENVIRONMENT = document.body.dataset.websiteEnv,
        LOCALE__COUNTRY = document.body.dataset.localeCountry,
        COUNTRY__BACKEND = document.body.dataset.geo;

    let element = {
        widgetTitle: "Search form",
        widgetId: widgetId,
        widgetHandler: widgetHandler,
        widgetPosition: widgetPosition
    }

    let pageAffLinkClickIndex = storage.getPageAffLinkClickIndex();
    pageAffLinkClickIndex++;
    storage.setPageAffLinkClickIndex(pageAffLinkClickIndex);

    searchAffLinkClickIndex++;

    let btn = item.querySelector(`.item__link`);
    let btnName = btn ? btn.innerHTML : `Popular search result`;

    let data = {
        score: JSON.parse(item.dataset.score),
        titleShort: JSON.parse(item.dataset.titleShort),
        titleLong: JSON.parse(item.dataset.titleLong),
        casino: {
            casinoId: JSON.parse(item.dataset.casinoId),
            name: JSON.parse(item.dataset.name),
            domain: JSON.parse(item.dataset.domain),
        },
        affiliateUrl: JSON.parse(item.dataset.affiliateUrl),
        id: JSON.parse(item.dataset.id),
        amountMax: JSON.parse(item.dataset.amountMax),
        percent: JSON.parse(item.dataset.percent),
        expired: JSON.parse(item.dataset.expired),
        specialButtonTitle: JSON.parse(item.dataset.specialButtonTitle),
        wageringRequirements: JSON.parse(item.dataset.wageringRequirements),
        depositMin: JSON.parse(item.dataset.depositMin),
        code: JSON.parse(item.dataset.code),
        label: JSON.parse(item.dataset.label),
        bonusCategories: JSON.parse(item.dataset.bonusCategories),
        bonusTypes: JSON.parse(item.dataset.bonusTypes),
        freeSpins: JSON.parse(item.dataset.freeSpins),
        currency: JSON.parse(item.dataset.currency),
        slots: JSON.parse(item.dataset.slots),
        casino_geo_rating: JSON.parse(+item.dataset.casino_geo_rating),
        casino_bonus_active_days_left: JSON.parse(+item.dataset.casino_bonus_active_days_left),
        casino_bonus_days_after_create: JSON.parse(+item.dataset.casino_bonus_days_after_create),
        casino_bonus_exclusive: JSON.parse(item.dataset.casino_bonus_exclusive),
        casino_bonus_code: JSON.parse(item.dataset.casino_bonus_code),
        casino_bonus_cashable: JSON.parse(item.dataset.casino_bonus_cashable),
        sponsored: JSON.parse(item.dataset.sponsored ? true : false)
    }

    dataLayer.push(Object.assign(
        {
            'event_id': `d-v1-${item.dataset.widget_list_index}`,
            'event': 'addEvents_clickAffLink',
            'event_cat': 'w_website_search_form_widget_new',
            'event_name': 'casino_visit',
            "casino_bonus_button_name": JSON.stringify(btnName),
            "casino_user_country_allowed": JSON.stringify(true),
            "page_afflink_click_index": JSON.stringify(pageAffLinkClickIndex),
            "widget_afflink_click_index": JSON.stringify(searchAffLinkClickIndex),
            "widget_list_index": JSON.stringify(item.dataset.widget_list_index),
            "website_domain": JSON.stringify(document.location.hostname),
        },
        {
            "page_current_path": JSON.stringify(PAGE__CURRENT__PATH),
            "page_url": JSON.stringify(PAGE__URL),
            "page_url_full": JSON.stringify(PAGE__URL__FULL),
            "page_group": JSON.stringify(EVENT__CAT),
            "widget_title": JSON.stringify(element.widgetTitle),
            "widget_id": JSON.stringify(element.widgetId),
            "page_route_id": JSON.stringify(ROUTE__ID),
            "widget_handler": JSON.stringify(element.widgetHandler),
            "widget_position": JSON.stringify(element.widgetPosition),
            "casino_list_user_country": JSON.stringify(COUNTRY__BACKEND),
            "casino_user_country": JSON.stringify(COUNTRY__BACKEND),
            "casino_list_for_geo": JSON.stringify(element.widgetBonusCountry ? element.widgetBonusCountry : element.widgetCasinoCountry ? element.widgetCasinoCountry : false)
        },
        {
            "casino_bonus_title_short": JSON.stringify(data.titleShort ? data.titleShort : ''),
            "casino_bonus_title_short_strlen": JSON.stringify(data.titleShort ? data.titleShort.length : 0),
            "casino_id": JSON.stringify(data.casino.casinoId),
            "casino_name": JSON.stringify(data.casino.name),
            "casino_domain": JSON.stringify(data.casino.domain),
            "casino_bonus_amount_max": JSON.stringify(data.amountMax && !isNaN(parseInt(data.amountMax)) ? parseInt(data.amountMax) : 0),
            "casino_bonus_percent": JSON.stringify(data.percent ? data.percent : 0),
            "casino_bonus_expired": JSON.stringify(!!data.expired),
            "casino_bonus_id": JSON.stringify(data.id),
            "casino_domain_bonus_id": JSON.stringify(`${data.casino.domain}_${data.id}`),
            "casino_score_geo": JSON.stringify(data.score.toFixed(1)),
            "casino_afflink_exist": JSON.stringify(!!data.affiliateUrl),
            "casino_bonus_wagering_requirements": JSON.stringify(data.wageringRequirements && !isNaN(parseInt(data.wageringRequirements)) ? parseInt(data.wageringRequirements) : 0),
            "casino_bonus_deposit_min": JSON.stringify(parseInt(data.depositMin)),
            "casino_bonus_code_exist": JSON.stringify(!!data.code),
            "casino_bonus_label_exist": JSON.stringify(!!data.label),
            "casino_bonus_category": JSON.stringify(data.bonusCategories && Array.isArray(data.bonusCategories) ? data.bonusCategories.map(item => item.name) : ''),
            "casino_bonus_label": JSON.stringify(data.label ? data.label : "Not Set"),
            "casino_bonus_type": JSON.stringify(data.bonusTypes && Array.isArray(data.bonusTypes) ? data.bonusTypes.map(item => item.name) : ''),
            "casino_bonus_free_spins": JSON.stringify(data.freeSpins ? +data.freeSpins : 0),
            "casino_score_geo_text": JSON.stringify(casinoScoreGeoText),
            "casino_bonus_currency": JSON.stringify(data.currency),
            "casino_bonus_active": JSON.stringify(false),
            "casino_bonus_slots": JSON.stringify(data.slots),
            "casino_bonus_category_display": JSON.stringify("Not Set"),
            "casino_geo_rating": JSON.stringify(data.casino_geo_rating ? +data.casino_geo_rating : 0),
            "casino_bonus_active_days_left": JSON.stringify(+data.casino_bonus_active_days_left),
            "casino_bonus_days_after_create": JSON.stringify(+data.casino_bonus_days_after_create),
            "casino_bonus_exclusive": JSON.stringify(data.casino_bonus_exclusive),
            "casino_bonus_code": JSON.stringify(data.casino_bonus_code),
            "casino_bonus_cashable": JSON.stringify(data.casino_bonus_cashable),
            "sponsored": JSON.stringify(data.sponsored ? true : false)
        }, utmParamsSearch())
    );
}
// searchAmplitudeClick

const searchDropdownSearchForm = document.querySelector(`.frontSearch #searchDropdown`);
searchDropdownSearchForm && searchFormFuncSearchForm();

let LOCALE_COUNTRY;
document.addEventListener('DOMContentLoaded', () => {
	LOCALE_COUNTRY = document.querySelector(`body`).dataset.localeCountry.toLowerCase();
	restrictedCountriesShowMore();
})
const getRestrictedCountries = async (domain, path) => {
	let response = await fetch(`/api/restricted_countries/${domain}`, {
		method: 'POST',
		headers: {
			'Content-Type': 'application/x-www-form-urlencoded'
		}
	});

	let result = await response.json();
	if (result.length) {
		result = result
			.sort((a, b) => (a.name > b.name) ? 1 : ((b.name > a.name) ? -1 : 0))
			.map(data => {
				if (data.name === `Metropolitan France`)
					data.alpha2 = `fr`;

				let country = data.name;
				switch (country) {
					case 'United States':
						country = 'USA';
						break;
					case 'United Kingdom':
						country = 'UK';
						break;
					case 'Russian Federation':
						country = 'Russia';
						break;
					case 'United Arab Emirates':
						country = 'UAE';
						break;
					case 'Viet Nam':
						country = 'Vietnam';
						break;
				}

				return `<div class="casinoAllowedCountriesWidget__item">
                    <a data-blank="no" rel="nofollow" data-name="external--link" data-href="/${path}/${data.slug}" class="casinoAllowedCountriesWidget__item--link">
                    <div class="casinoAllowedCountriesWidget__item--img-wrapper">
                        <img class="casinoAllowedCountriesWidget__item--flag" src="/build/img/flags/${data.alpha2.toLowerCase()}.svg" alt="${data.alpha2.toLowerCase()}" loading="lazy">
                        <svg class="icon_cancel" width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                            <path d="M12.0002 10.586L16.9502 5.63599L18.3642 7.04999L13.4142 12L18.3642 16.95L16.9502 18.364L12.0002 13.414L7.05023 18.364L5.63623 16.95L10.5862 12L5.63623 7.04999L7.05023 5.63599L12.0002 10.586Z"
                            fill="#FF455B"/>
                        </svg>
                    </div>
                    <span class="casinoAllowedCountriesWidget__item--title">${country}</span>
                    </a>
                </div>`;
			})
			.join('');
		return result;
	}
};
const restrictedCountriesShowMore = () => {
	let allowedCountriesAll = document.querySelector('.casinoAllowedCountriesWidget__btn');
	if (allowedCountriesAll) {
		allowedCountriesAll.addEventListener('click', async e => {
			let more = document.querySelector('.casinoAllowedCountriesWidget__items'),
				path = allowedCountriesAll.dataset.path,
				domain = document.location.pathname;

			domain = domain.replace('/online-casinos/', '').replace('/recenzje/', '').replace('/casino-bonuses/', '');

			if (!allowedCountriesAll.classList.contains('items__all')) {
				allowedCountriesAll.classList.add('items__all');
				const allCOuntries = await getRestrictedCountries(domain, path);
				more.innerHTML = allCOuntries;
			}

			if (allowedCountriesAll.classList.contains('active')) {
				allowedCountriesAll.classList.remove('active');
				allowedCountriesAll.querySelector('span').innerHTML = LOCALE_COUNTRY === `pl` ? `Pokaż więcej` : 'Show more';
				more.classList.remove('all');
			} else {
				allowedCountriesAll.classList.add('active');
				allowedCountriesAll.querySelector('span').innerHTML = LOCALE_COUNTRY === `pl` ? `Pokaż mniej` : 'Show less';
				more.classList.add('all');
			}
		})
	}
}


import {
	getUserReviewPaginated,
	updateReply,
	storeReply,
	storeUserReviewLike,
	deleteUserReviewLike
} from "userReviewApi";
import {authPopup} from "authPopup";
import {__translate as __cucw_translate} from "translate";
import {getLocaleCountry as __cucw_localeCountry, utmParams as utmParamsUserComment} from "globals";

class CasinoUserCommentWidget {

    constructor() {
		this.sortType = 'newest';
		this.showMorePage = 2;
		this.commentTextOutput = document.querySelectorAll('.comment_text-output');
		this.commentProsOutput = document.querySelectorAll('.pros_text-output');
		this.commentConsOutput = document.querySelectorAll('.cons_text-output');
		this.commentReplyOutput = document.querySelectorAll('.reply_text-output');
		this.helpfulLike = document.querySelectorAll('.helpfulLike_click');
		this.helpfulUnlike = document.querySelectorAll('.helpfulUnlike_click');
		this.fastReplyButton = document.querySelectorAll('.fastReplyButton');
		this.editReplyText = document.querySelectorAll('.edit_reply-text');
		this.editErrors = document.querySelectorAll('.edit_errors');
		this.sendReplyButton = document.querySelectorAll('.sendReplyButton');
		this.casinoReplyBox = document.querySelectorAll('.casino_reply-box');
		this.casinoUserCommentItem = document.querySelectorAll('.casinoUserComment_item');
		this.casinoUserCommentShowMoreButton = document.getElementById('casinoUserCommentShowMoreButton');
		this.casinoUserCommentSort = document.getElementById('casinoUserCommentSort');
		this.casinoUserCommentSortOptions = document.getElementById('casinoUserCommentSortOptions');
		this.casinoUserCommentSortSelected = document.getElementById('casinoUserCommentSortSelected');
		this.casinoUserCommentSortArrow = document.getElementById('casinoUserCommentSortArrow');
		this.casinoUserCommentAppendBox = document.getElementById('casinoUserCommentAppendBox');
		this.casinoScoreWidget = document.getElementById('casinoScoreWidget');
	}

	/**
	 *
	 * @param elements
	 */
	addTextShowMore(elements) {
		elements.forEach(element => {
			if (element.innerText.length > 200) {
				const truncatedText = element.innerText.slice(0, 200);
				const remainingText = element.innerText.slice(200);

				const hiddenText = document.createElement('span');
				hiddenText.classList.add('hidden_text');
				hiddenText.innerText = truncatedText;

				const showMoreBtn = document.createElement('button');
				showMoreBtn.classList.add('show_more-btn');
				showMoreBtn.innerText = `${__cucw_translate('Show more', __cucw_localeCountry()) ?? 'Show more'}`;

                showMoreBtn.addEventListener('click', () => {
                    if (hiddenText.innerText === truncatedText) {
                        hiddenText.innerText = truncatedText + remainingText;
                        showMoreBtn.innerText = `${__cucw_translate('Show less', __cucw_localeCountry()) ?? 'Show less'}`;
                        showMoreBtn.classList.add('show_less');
                    } else {
                        hiddenText.innerText = truncatedText;
                        showMoreBtn.innerText = `${__cucw_translate('Show more', __cucw_localeCountry()) ?? 'Show more'}`;
                        showMoreBtn.classList.remove('show_less');
                    }
                });

				element.innerHTML = '';
				element.appendChild(hiddenText);
				element.appendChild(showMoreBtn);
			}
		});
	}

    sort() {
        if (this.casinoUserCommentSort) {
            this.casinoUserCommentSort.addEventListener('click', () => {
                if (this.casinoUserCommentSortOptions.style.visibility === 'visible') {
                    this.sortStyle(
                        'hidden',
                        '0',
                        '0deg'
                    );
                } else {
                    this.sortStyle(
                        'visible',
                        '1',
                        '180deg'
                    );
                }
            });

			this.showMorePage = 1;

            Array.from(this.casinoUserCommentSortOptions.children).forEach((el) => {
                el.addEventListener('click', async () => {
                    this.casinoUserCommentSortSelected.innerText = el.textContent;
                    this.sortType = el.textContent.toLowerCase().replace(' ', '-');

					this.toggleActiveOption(
						el,
						this.casinoUserCommentSortOptions.children
					);

                    let data = await getUserReviewPaginated(
                        this.sortType,
                        document.body.dataset.casinoId,
                        1
                    );

                    this.appendReviews(
                        data['userReviews'],
                        true
                    );
                });
            });
        }
    }

	/**
	 *
	 * @param activate
	 * @param elements
	 */
	toggleActiveOption(activate, elements) {
		Array.from(elements).forEach(el => {
			el.classList.remove('active');
		});

		activate.classList.add('active');
	}

    /**
     *
     * @param data
     * @param isSort
     */
    appendReviews(data, isSort = false) {
        if (isSort) {
            this.casinoUserCommentAppendBox.innerHTML = '';
        } else {
            document.querySelector('.casinoUserComment_showMore-container').remove();
        }

        data.forEach((data, index) => {
            this.casinoUserCommentAppendBox.innerHTML += `
                <div class="casinoUserComment_item casinoUserComment_item-fadeIn" data-user-review-id=${data['id']}>
                <div class="casinoUserComment_item-info">
                    <div class="user">
                        <div class="avatar"
                             style="background-image: url(${data['avatar']});"></div>
                        <div class="info">
                            <div class="base_info">
                                <p class="username">${data['username']}</p>
                                    ${data['alpha2'] ? `
                                    <div class="flag"
                                         style="background-image: url('/build/img/flags/${data['alpha2'].toLowerCase() + '.svg'}');"></div>
                                    ` : ''}                               
                            </div>
                            <span class="reviews">${data['user_review_count']} reviews</span>
                        </div>
                    </div>
                    <div class="reviews_total">
                        <div class="stars_box">
                            <div class="stars_box-counter">
                                ${this.generateStars(parseFloat(data['score']))}
                            </div>
                            <span class="stars_box-total">
                            ${data['score']}
                        </span>
                        </div>
                        <p class="date">${this.dateConvert(data['created'])}</p>
                    </div>
                </div>
                <div class="casinoUserComment_item-info">
                    <div class="comment">
                        <p class="text comment_text-output">${data['comment']}</p>
                        ${data['pros'] ? `
                           <div class="pros_cons">
                              <p class="title title_pros">Pros:</p>
                              <p class="text pros_text-output">
                                  ${data['pros']}
                              </p>
                           </div>
                        ` : ''}
                      
                        ${data['cons'] ? `
                           <div class="pros_cons">
                              <p class="title title_cons">Pros:</p>
                              <p class="text pros_text-output">
                                  ${data['cons']}
                              </p>
                           </div>
                        ` : ''}
                    </div>

                    <div class="detailed_score">
                        <div class="option">
                            <p class="title">Promotions & Bonuses</p>
                            <span class="value">${data['detailed_score'].promotions_and_bonuses}</span>
                        </div>
                        <div class="option">
                            <p class="title">Deposits & Withdrawals</p>
                            <span class="value">${data['detailed_score'].deposits_and_withdrawals}</span>
                        </div>
                        <div class="option">
                            <p class="title">Games Variety</p>
                            <span class="value">${data['detailed_score'].games_variety}</span>
                        </div>
                        <div class="option">
                            <p class="title">Support</p>
                            <span class="value">${data['detailed_score'].support}</span>
                        </div>
                        <div class="option">
                            <p class="title">Website convenience</p>
                            <span class="value">${data['detailed_score'].website_convenience}</span>
                        </div>
                    </div>
                </div>
                <div class="casinoUserComment_item-info">
                   ${data['liked_by_auth'] ?
				`<p class="helpful helpfulUnlike_click" data-like="${data['likes']}">
                           <svg class="icon_helpful" width="20" height="20" viewBox="0 0 20 20" fill="none" xmlns="http://www.w3.org/2000/svg">
                               <g opacity="0.5" clip-path="url(#clip0_9630_89675)">
                                   <path d="M1.66927 7.49997H4.16927V17.5H1.66927C1.44826 17.5 1.2363 17.4122 1.08002 17.2559C0.923735 17.0996 0.835938 16.8877 0.835938 16.6666V8.3333C0.835937 8.11229 0.923735 7.90033 1.08002 7.74405C1.2363 7.58777 1.44826 7.49997 1.66927 7.49997ZM6.0801 6.42247L11.4134 1.08914C11.4843 1.01805 11.5785 0.974943 11.6786 0.967747C11.7788 0.960551 11.8781 0.989749 11.9584 1.04997L12.6693 1.5833C12.8667 1.73151 13.0158 1.93485 13.0978 2.16768C13.1798 2.40052 13.1911 2.65243 13.1301 2.89164L12.1693 6.66664H17.5026C17.9446 6.66664 18.3686 6.84223 18.6811 7.15479C18.9937 7.46735 19.1693 7.89128 19.1693 8.3333V10.0866C19.1695 10.3044 19.127 10.5202 19.0443 10.7216L16.4651 16.9841C16.4022 17.1368 16.2953 17.2674 16.1581 17.3592C16.0208 17.451 15.8594 17.5 15.6943 17.5H6.66927C6.44826 17.5 6.2363 17.4122 6.08002 17.2559C5.92374 17.0996 5.83594 16.8877 5.83594 16.6666V7.01164C5.83598 6.79064 5.92381 6.57871 6.0801 6.42247Z" fill="#4443b8"></path>
                               </g>
                           </svg>
                           ${data['likes'] ? `<span class="helpful_count" data-like="${data['likes']}">${data['likes']}</span>` : ''}    
                           <span class="text">Helpful</span>
                       </p>` :
				(!data['liked_by_auth'] && data['likes']) ?
					`
                       <p class="helpful helpfulLike_click" data-like="${data['likes']}">
                           <svg class="icon_helpful" width="20" height="20" viewBox="0 0 20 20" fill="none" xmlns="http://www.w3.org/2000/svg">
                               <g opacity="0.3" clip-path="url(#clip0_9630_89675)">
                                   <path d="M1.66927 7.49997H4.16927V17.5H1.66927C1.44826 17.5 1.2363 17.4122 1.08002 17.2559C0.923735 17.0996 0.835938 16.8877 0.835938 16.6666V8.3333C0.835937 8.11229 0.923735 7.90033 1.08002 7.74405C1.2363 7.58777 1.44826 7.49997 1.66927 7.49997ZM6.0801 6.42247L11.4134 1.08914C11.4843 1.01805 11.5785 0.974943 11.6786 0.967747C11.7788 0.960551 11.8781 0.989749 11.9584 1.04997L12.6693 1.5833C12.8667 1.73151 13.0158 1.93485 13.0978 2.16768C13.1798 2.40052 13.1911 2.65243 13.1301 2.89164L12.1693 6.66664H17.5026C17.9446 6.66664 18.3686 6.84223 18.6811 7.15479C18.9937 7.46735 19.1693 7.89128 19.1693 8.3333V10.0866C19.1695 10.3044 19.127 10.5202 19.0443 10.7216L16.4651 16.9841C16.4022 17.1368 16.2953 17.2674 16.1581 17.3592C16.0208 17.451 15.8594 17.5 15.6943 17.5H6.66927C6.44826 17.5 6.2363 17.4122 6.08002 17.2559C5.92374 17.0996 5.83594 16.8877 5.83594 16.6666V7.01164C5.83598 6.79064 5.92381 6.57871 6.0801 6.42247Z" fill="#5554de"></path>
                               </g>
                           </svg>
                           ${data['likes'] ? `<span class="helpful_count" data-like="${data['likes']}">${data['likes']}</span>` : ''}  
                           <span class="text">Helpful</span>
                       </p>
                       ` : `
                       <p class="helpful helpfulLike_click" data-like="0">
                           <svg class="icon_helpful" width="20" height="20" viewBox="0 0 20 20" fill="none" xmlns="http://www.w3.org/2000/svg">
                               <g opacity="0.3" clip-path="url(#clip0_9630_89675)">
                                   <path d="M1.66927 7.49997H4.16927V17.5H1.66927C1.44826 17.5 1.2363 17.4122 1.08002 17.2559C0.923735 17.0996 0.835938 16.8877 0.835938 16.6666V8.3333C0.835937 8.11229 0.923735 7.90033 1.08002 7.74405C1.2363 7.58777 1.44826 7.49997 1.66927 7.49997ZM6.0801 6.42247L11.4134 1.08914C11.4843 1.01805 11.5785 0.974943 11.6786 0.967747C11.7788 0.960551 11.8781 0.989749 11.9584 1.04997L12.6693 1.5833C12.8667 1.73151 13.0158 1.93485 13.0978 2.16768C13.1798 2.40052 13.1911 2.65243 13.1301 2.89164L12.1693 6.66664H17.5026C17.9446 6.66664 18.3686 6.84223 18.6811 7.15479C18.9937 7.46735 19.1693 7.89128 19.1693 8.3333V10.0866C19.1695 10.3044 19.127 10.5202 19.0443 10.7216L16.4651 16.9841C16.4022 17.1368 16.2953 17.2674 16.1581 17.3592C16.0208 17.451 15.8594 17.5 15.6943 17.5H6.66927C6.44826 17.5 6.2363 17.4122 6.08002 17.2559C5.92374 17.0996 5.83594 16.8877 5.83594 16.6666V7.01164C5.83598 6.79064 5.92381 6.57871 6.0801 6.42247Z" fill="#b5b5b5"></path>
                               </g>
                           </svg>
                           <span class="text">Helpful</span>
                       </p>
                   `}
                </div>
            `;
		});

        this.casinoUserCommentAppendBox.innerHTML += `
            ${this.shouldShowMore(data, isSort) ?
            `<div class="casinoUserComment_showMore-container">
                    <button id="casinoUserCommentShowMoreButton" class="btn-show-more">${__cucw_translate('Show more', __cucw_localeCountry()) ?? 'Show more'}</button>
            </div>` : ''}`;

			this.shouldShowMore(data, isSort) ? this.showMorePage++ : null;

		this.addTextShowMore(document.querySelectorAll('.comment_text-output'));
		this.addTextShowMore(document.querySelectorAll('.reply_text-output'));
		this.showMoreItemsClick(document.getElementById('casinoUserCommentShowMoreButton'));
		this.toggleHelpfulClick(document.querySelectorAll('.helpfulLike_click'));
		this.toggleHelpfulClick(document.querySelectorAll('.helpfulUnlike_click'));
	}

	/**
	 *
	 * @param inputDateStr
	 * @returns {string}
	 */
	dateConvert(inputDateStr) {
		const inputDate = new Date(inputDateStr);

		const months = [
			'January',
			'February',
			'March',
			'April',
			'May',
			'June',
			'July',
			'August',
			'September',
			'October',
			'November',
			'December'
		];

		const day = inputDate.getDate();
		const month = months[inputDate.getMonth()];
		const year = inputDate.getFullYear();

		return `${day} ${month}, ${year}`;
	}

	/**
	 *
	 * @param rating
	 * @returns {string}
	 */
	generateStars(rating) {
		const filledStars = Math.floor(rating);
		const halfStar = rating - filledStars >= 0.5;
		const emptyStars = 5 - (filledStars + (halfStar ? 1 : 0));

		const decimalPart = rating.toFixed(2);
		const tenthsPlace = decimalPart.slice(-2, -1);

		let emptyStarsRoundedNumber;

		if (parseInt(tenthsPlace) >= 5) {
			emptyStarsRoundedNumber = Math.floor(emptyStars);
		} else {
			emptyStarsRoundedNumber = Math.ceil(emptyStars);
		}

		let starsHtml = '';

		for (let i = 0; i < filledStars; i++) {
			starsHtml += `
              <svg class="icon_star-review" width="32" height="32" viewBox="0 0 32 32" fill="none" xmlns="http://www.w3.org/2000/svg">
                  <path d="M15.3333 5.3335L18.9056 12.2606L26.6667 13.4821L21.1133 18.9848L22.3377 26.6668L15.3333 23.1406L8.32895 26.6668L9.55333 18.9848L4 13.4821L11.7611 12.2606L15.3333 5.3335Z" fill="#ffd700"></path>
                  <path fill-rule="evenodd" clip-rule="evenodd" d="M16 4C16.4047 4 16.7751 4.23745 16.9591 4.61469L20.1531 11.1651L27.0923 12.3202C27.492 12.3868 27.8222 12.6822 27.9473 13.085C28.0723 13.4878 27.971 13.9299 27.6851 14.2296L22.7198 19.4331L23.8145 26.6975C23.8776 27.1158 23.7112 27.5358 23.3838 27.7848C23.0564 28.0337 22.6234 28.0695 22.2627 27.8775L16 24.543L9.7373 27.8775C9.37663 28.0695 8.94355 28.0337 8.61618 27.7848C8.28881 27.5358 8.12243 27.1158 8.18548 26.6975L9.28021 19.4331L4.31491 14.2296C4.02897 13.9299 3.92768 13.4878 4.05273 13.085C4.17777 12.6822 4.50803 12.3868 4.90766 12.3202L11.8469 11.1651L15.0409 4.61469C15.2249 4.23745 15.5953 4 16 4ZM16 7.60619L13.5161 12.7003C13.3597 13.0212 13.0661 13.2445 12.7262 13.301L7.32961 14.1993L11.191 18.246C11.4342 18.5009 11.5464 18.8621 11.4928 19.218L10.6414 24.8673L15.5118 22.2741C15.8186 22.1108 16.1814 22.1108 16.4882 22.2741L21.3586 24.8673L20.5072 19.218C20.4536 18.8621 20.5658 18.5009 20.809 18.246L24.6704 14.1993L19.2738 13.301C18.9339 13.2445 18.6403 13.0212 18.4839 12.7003L16 7.60619Z" fill="#ffd700"></path>
              </svg>
            `;
		}

		if (halfStar) {
			starsHtml += `
              <svg class="icon_star-review-half" width="32" height="32" viewBox="0 0 32 32" fill="none" xmlns="http://www.w3.org/2000/svg">
                <mask id="mask0_101_8" style="mask-type:alpha" maskUnits="userSpaceOnUse" x="4" y="4" width="24" height="24">
                    <path d="M15.3333 5.33333L18.9056 12.2604L26.6667 13.4819L21.1133 18.9846L22.3377 26.6667L15.3333 23.1404L8.32895 26.6667L9.55333 18.9846L4 13.4819L11.7611 12.2604L15.3333 5.33333Z" fill="#F0D800"></path>
                    <path fill-rule="evenodd" clip-rule="evenodd" d="M16 4C16.4047 4 16.7751 4.23745 16.9591 4.61469L20.1531 11.1651L27.0923 12.3202C27.492 12.3868 27.8222 12.6822 27.9473 13.085C28.0723 13.4878 27.971 13.9299 27.6851 14.2296L22.7198 19.4331L23.8145 26.6975C23.8776 27.1158 23.7112 27.5358 23.3838 27.7848C23.0564 28.0337 22.6234 28.0695 22.2627 27.8775L16 24.543L9.7373 27.8775C9.37663 28.0695 8.94355 28.0337 8.61618 27.7848C8.28881 27.5358 8.12243 27.1158 8.18548 26.6975L9.28021 19.4331L4.31491 14.2296C4.02897 13.9299 3.92768 13.4878 4.05273 13.085C4.17777 12.6822 4.50803 12.3868 4.90766 12.3202L11.8469 11.1651L15.0409 4.61469C15.2249 4.23745 15.5953 4 16 4ZM16 7.60619L13.5161 12.7003C13.3597 13.0212 13.0661 13.2445 12.7262 13.301L7.32961 14.1993L11.191 18.246C11.4342 18.5009 11.5464 18.8621 11.4928 19.218L10.6414 24.8673L15.5118 22.2741C15.8186 22.1108 16.1814 22.1108 16.4882 22.2741L21.3586 24.8673L20.5072 19.218C20.4536 18.8621 20.5658 18.5009 20.809 18.246L24.6704 14.1993L19.2738 13.301C18.9339 13.2445 18.6403 13.0212 18.4839 12.7003L16 7.60619Z" fill="#F0D800"></path>
                </mask>
                <g mask="url(#mask0_101_8)">
                    <rect x="3" y="4" width="13" height="26" fill="#F0D800"></rect>
                    <rect x="16" y="3" width="19" height="27" fill="#D9D9D9"></rect>
                </g>
              </svg>
            `;
		}

		for (let i = 0; i < emptyStarsRoundedNumber; i++) {
			starsHtml += `
              <svg class="icon_star-review" width="32" height="32" viewBox="0 0 32 32" fill="none" xmlns="http://www.w3.org/2000/svg">
                 <path d="M15.3333 5.3335L18.9056 12.2606L26.6667 13.4821L21.1133 18.9848L22.3377 26.6668L15.3333 23.1406L8.32895 26.6668L9.55333 18.9848L4 13.4821L11.7611 12.2606L15.3333 5.3335Z" fill="#d9d9d9"></path>
                 <path fill-rule="evenodd" clip-rule="evenodd" d="M16 4C16.4047 4 16.7751 4.23745 16.9591 4.61469L20.1531 11.1651L27.0923 12.3202C27.492 12.3868 27.8222 12.6822 27.9473 13.085C28.0723 13.4878 27.971 13.9299 27.6851 14.2296L22.7198 19.4331L23.8145 26.6975C23.8776 27.1158 23.7112 27.5358 23.3838 27.7848C23.0564 28.0337 22.6234 28.0695 22.2627 27.8775L16 24.543L9.7373 27.8775C9.37663 28.0695 8.94355 28.0337 8.61618 27.7848C8.28881 27.5358 8.12243 27.1158 8.18548 26.6975L9.28021 19.4331L4.31491 14.2296C4.02897 13.9299 3.92768 13.4878 4.05273 13.085C4.17777 12.6822 4.50803 12.3868 4.90766 12.3202L11.8469 11.1651L15.0409 4.61469C15.2249 4.23745 15.5953 4 16 4ZM16 7.60619L13.5161 12.7003C13.3597 13.0212 13.0661 13.2445 12.7262 13.301L7.32961 14.1993L11.191 18.246C11.4342 18.5009 11.5464 18.8621 11.4928 19.218L10.6414 24.8673L15.5118 22.2741C15.8186 22.1108 16.1814 22.1108 16.4882 22.2741L21.3586 24.8673L20.5072 19.218C20.4536 18.8621 20.5658 18.5009 20.809 18.246L24.6704 14.1993L19.2738 13.301C18.9339 13.2445 18.6403 13.0212 18.4839 12.7003L16 7.60619Z" fill="#d9d9d9"></path>
              </svg>
            `;
		}

		return starsHtml;
	}

	/**
	 *
	 * @param visibility
	 * @param opacity
	 * @param rotate
	 */
	sortStyle(visibility, opacity, rotate) {
		this.casinoUserCommentSortOptions.style.visibility = visibility;
		this.casinoUserCommentSortOptions.style.opacity = opacity;
		this.casinoUserCommentSortArrow.style.rotate = rotate;
	}

    /**
     *
     * @param button
     */
    showMoreItemsClick(button) {
        button ? button.addEventListener('click', async () => {
            let data = await getUserReviewPaginated(
                this.sortType,
                document.body.dataset.casinoId,
                this.showMorePage
            );

            this.appendReviews(data['userReviews']);
        }) : null;
    }

	/**
	 *
	 * @param elements
	 */
	toggleHelpfulClick(elements) {
		const handleLike = async (element, action) => {
			const userReviewId = element.closest('.casinoUserComment_item').dataset.userReviewId;
			const likeValue = parseInt(element.dataset.like);

			if (storage.getAuthToken()) {
				if (action === 'like') {
					await storeUserReviewLike(userReviewId);
				} else if (action === 'unlike') {
					await deleteUserReviewLike(userReviewId);
				}

				const fillStyle = action === 'like' ? '#4443b8' : '#5554de';
				const newLikeValue = action === 'like' ? likeValue + 1 : Math.max(0, likeValue - 1);

				element.querySelector('.icon_helpful path').style.fill = fillStyle;
				element.classList.toggle('helpfulLike_click');
				element.classList.toggle('helpfulUnlike_click');
				element.setAttribute('data-like', newLikeValue);
				element.innerHTML = `
                <svg class="icon_helpful" width="20" height="20" viewBox="0 0 20 20" fill="none" xmlns="http://www.w3.org/2000/svg">
                    <g opacity="${action === 'like' ? '0.5' : '0.3'}" clip-path="url(#clip0_9630_89675)">
                        <path d="M1.66927 7.49997H4.16927V17.5H1.66927C1.44826 17.5 1.2363 17.4122 1.08002 17.2559C0.923735 17.0996 0.835938 16.8877 0.835938 16.6666V8.3333C0.835937 8.11229 0.923735 7.90033 1.08002 7.74405C1.2363 7.58777 1.44826 7.49997 1.66927 7.49997ZM6.0801 6.42247L11.4134 1.08914C11.4843 1.01805 11.5785 0.974943 11.6786 0.967747C11.7788 0.960551 11.8781 0.989749 11.9584 1.04997L12.6693 1.5833C12.8667 1.73151 13.0158 1.93485 13.0978 2.16768C13.1798 2.40052 13.1911 2.65243 13.1301 2.89164L12.1693 6.66664H17.5026C17.9446 6.66664 18.3686 6.84223 18.6811 7.15479C18.9937 7.46735 19.1693 7.89128 19.1693 8.3333V10.0866C19.1695 10.3044 19.127 10.5202 19.0443 10.7216L16.4651 16.9841C16.4022 17.1368 16.2953 17.2674 16.1581 17.3592C16.0208 17.451 15.8594 17.5 15.6943 17.5H6.66927C6.44826 17.5 6.2363 17.4122 6.08002 17.2559C5.92374 17.0996 5.83594 16.8877 5.83594 16.6666V7.01164C5.83598 6.79064 5.92381 6.57871 6.0801 6.42247Z"
                            fill="${fillStyle}"/>
                    </g>
                </svg>
                <span class="helpful_count">${newLikeValue}</span>
            `;
			} else {
				authPopup.generateHTMLAdapter('mainHTML');
			}
		};

		elements.forEach(element => {
			element.addEventListener('click', async () => {
				if (element.classList.contains('helpfulLike_click')) {
					await handleLike(element, 'like');
				} else if (element.classList.contains('helpfulUnlike_click')) {
					await handleLike(element, 'unlike');
				}
			});
		});
	}

	scrollToByHash() {
		const hash = window.location.hash.slice(1);

		if (!hash) {
			return;
		}

		const element = hash ? document.getElementById(hash) : null;

        const scrollOptions = {
            behavior: 'smooth',
            block: 'center',
            inline: 'center',
        };

        if (element && !element.classList.contains('casinoUserComment_item-hidden')) {
            setTimeout(() => {
                element.scrollIntoView(scrollOptions);
            }, 500);
        } else {
            setTimeout(() => {
                this.casinoScoreWidget.scrollIntoView(scrollOptions);
            }, 500);
        }
    }

	/**
	 *
	 * @param fastReplyButton
	 * @param errors
	 * @param options
	 */
	replyClick(fastReplyButton, errors, options) {
		fastReplyButton.forEach((button, index) => {
			if (!button) return;

			button.addEventListener('click', () => {
				const casinoReplyBox = options.casinoReplyBox[index];
				const sendReplyButton = options.sendReplyButton[index];
				const editReplyText = options.editReplyText[index];
				const userId = options.casinoUserCommentItem[index].dataset.userId;
				const userReviewId = options.casinoUserCommentItem[index].dataset.userReviewId;
				const casinoId = document.body.dataset.casinoId;

				casinoReplyBox.style.display = 'block';
				button.style.display = 'none';

				sendReplyButton.addEventListener('click', () => {
					const buttonType = sendReplyButton.dataset.buttonType;
					if (buttonType === 'edit') {
						return updateReply(userReviewId, casinoId, editReplyText.value).then((resp) => {
							!resp.update ? errors[index].innerText = resp.errors['text'] :
								options.casinoReplyBox[index].innerHTML = '<div class="success_message">Thank you for your reply!</div>';
						});
					}

					return storeReply(userReviewId, casinoId, editReplyText.value).then((resp) => {
						!resp.store ? errors[index].innerText = resp.errors['text'] :
							options.casinoReplyBox[index].innerHTML = '<div class="success_message">Thank you for your reply!</div>';
					});
				});
			});
		});
	}

	generate() {
		this.addTextShowMore(this.commentTextOutput);
		this.addTextShowMore(this.commentReplyOutput);
		this.showMoreItemsClick(this.casinoUserCommentShowMoreButton);
		this.toggleHelpfulClick(this.helpfulLike);
		this.toggleHelpfulClick(this.helpfulUnlike);
		this.scrollToByHash();
		this.sort();
		this.showMorePage = 2;

		this.replyClick(
			this.fastReplyButton,
			this.editErrors,
			{
				casinoReplyBox: this.casinoReplyBox,
				sendReplyButton: this.sendReplyButton,
				editReplyText: this.editReplyText,
				casinoUserCommentItem: this.casinoUserCommentItem,
			}
		);
	}

	shouldShowMore(data, isSort) {
		const page = isSort ? 1 : this.showMorePage;

		return page === 1 && data.length >= 20 || page > 1 && data.length >= 5;
	}
}

const casinoUserCommentWidget = new CasinoUserCommentWidget();

if (document.getElementById('casinoUserCommentWidget')) {
    casinoUserCommentWidget.generate()
}



import {__translate as __int_translate} from "translate";

class IntroWidget {

	/**
	 *
	 * @type {Element}
	 */
	prime = document.querySelector('.prime-bg');

	/**
	 *
	 * @type {Element}
	 */
	header = document.querySelector('.header');

	/**
	 *
	 * @type {NodeListOf<Element>}
	 */
	introBlocks = document.querySelectorAll(`.block__intro`);

	/**
	 *
	 * @type {Element}
	 */
	buttonViewBonusesWidget = document.querySelector('.buttonViewBonusesWidget__more-bonuses__btn');

	/**
	 *
	 * @type {Element}
	 */
	blockMoreContent = document.querySelector('.block__more--content');

	/**
	 *
	 * @type {NodeListOf<Element>}
	 */
	introDescriptionParagraph = document.querySelectorAll('[data-widget-handler="IntroWidget"] .block__intro.block__more--hide');

	/**
	 *
	 * @type {string}
	 */
	route = document.body.dataset.routeBonus;

	/**
	 *
	 * @type {Element}
	 */
	restrictedBlock = document.querySelector(`.restrictedBlock`);

	/**
	 *
     @type {boolean}
	 */
	casinoRouteDesktop = this.route === `p_casino` && this.restrictedBlock && window.innerWidth >= 992;

	moreBtnClick() {
		if (this.buttonViewBonusesWidget) {
			this.buttonViewBonusesWidget.addEventListener('click', (e) => {
				e.preventDefault();

				const blockHeight = this.prime.getBoundingClientRect().height;

				window.scrollTo({
					top: window.pageYOffset + blockHeight,
					behavior: 'smooth'
				});
			})
		}
	}

	onLoadDescriptionShowMore() {
		if (this.introDescriptionParagraph.length && !this.casinoRouteDesktop) {
			this.introDescriptionParagraph.forEach(block => {
				let children = [...block.children];

				block.parentElement.classList.remove('intro__more-btn--show');

				if (children.length) {
					const countOfChars = 480;
					let previewText = [];
					let indexOfLastWhiteSpace;
					let newPreviewText;
					let textMore = false;

					block.innerHTML = ``;

					const getNearestWhiteSpaceIndex = (index, charts) => {
						if (index >= charts.length) return -1;

						let char = charts[index];
						if (char !== ` ` && char !== `.` && char !== `!` && char !== `?`) getNearestWhiteSpaceIndex((index + 1), charts);
						else indexOfLastWhiteSpace = index;
					}

					for (let i = 0; i < children.length; i++) {
						if (children[i].tagName === `TABLE`) continue;

						let itemChars = (children[i].innerHTML.split(``) || []);
						let previewTextLength = previewText.length;
						previewText = previewText.concat([` `], itemChars);

						if (previewText.length >= countOfChars) {
							textMore = true;
							getNearestWhiteSpaceIndex((countOfChars - 1), previewText);
							newPreviewText = previewText.slice(previewTextLength, indexOfLastWhiteSpace).join(``);
							break;
						} else {
							block.append(children[i]);
						}
					}

					if (textMore) {
						let previewWrap = document.createElement(`p`);
						previewWrap.innerHTML = newPreviewText + `...`;

						let btnWrap = document.createElement('div');
						btnWrap.className = 'intro__more-btn-wrapper'

						const showMoreBtn = document.createElement(`span`);
						const LOCALE_COUNTRY = document.querySelector(`body`).dataset.localeCountry.toLowerCase();
						showMoreBtn.innerHTML = __int_translate("Read more", LOCALE_COUNTRY);
						showMoreBtn.className = `intro__more-btn`;
						showMoreBtn.addEventListener(`click`, () => {
							block.innerHTML = ``;
							children.forEach(item => block.append(item));
							btnWrap.remove();
							block.parentElement.classList.remove('intro__more-btn--show');
							this.introBlocks[0].style.cssText = 'max-height: unset; overflow: unset;';
						});

						btnWrap.append(showMoreBtn);

						block.parentElement.classList.add('intro__more-btn--show');
						block.append(btnWrap);

						block.append(previewWrap);
					}
				}
			});
		} else {
			if (this.introBlocks.length) this.introBlocks[0].style.cssText = 'max-height: unset; overflow: unset;';
		}
	}

	casinoRoute() {
		if (this.casinoRouteDesktop) {
			if (this.introDescriptionParagraph.length) {
				this.introDescriptionParagraph.forEach(block => {
					block.classList.remove(`block__more--hide`);
				});
			}
		}
	}
}

const introWidget = new IntroWidget();

introWidget.casinoRoute();
introWidget.moreBtnClick();
introWidget.onLoadDescriptionShowMore();



class CasinoBankingAndPayoutsWidget{
	reviewMoreBtns = document.querySelectorAll(`button[data-id=reviewMore]`);
	showMoreBtns = document.querySelectorAll('.casinoBankingAndPayoutsWidget__more');

	init(){
		this.showMoreClickFn();
		this.reviewMoreBtnsFn();
	}

	reviewMoreBtnsFn(){
		if (this.reviewMoreBtns.length) {
			this.reviewMoreBtns.forEach(btn => {
				let table = btn.previousElementSibling,
					btnText = btn.querySelector(`.text`);

				btn.addEventListener(`click`, () => {
					table.classList.toggle(`shown`);

					btnText.innerHTML = btn.classList.contains(`shown`) ? `Show more` : `Show less`;
					if (LOCALE_COUNTRY === `fr`)
						btnText.innerHTML = btn.classList.contains(`shown`) ? `Montre plus` : `Montrer moins`;
					if (LOCALE_COUNTRY === `pl`)
						btnText.innerHTML = btn.classList.contains(`shown`) ? `Pokaż więcej` : `Pokaż mniej`;
					btn.classList.toggle(`shown`);
				})

			})
		}
	}

	showMoreClickFn(){
		if(this.showMoreBtns.length){
			this.showMoreBtns.forEach(el => {
				el.addEventListener('click', () => {
					const parentWrapper = el.closest('.casinoBankingAndPayoutsWidget__items');
					const visibleBlock = parentWrapper.querySelector('.casinoBankingAndPayoutsWidget__items-visible');
					const hiddenBlock = parentWrapper.querySelector('.casinoBankingAndPayoutsWidget__items-hidden');
					if (hiddenBlock.classList.contains('casinoBankingAndPayoutsWidget__items-hidden--active')) {
						hiddenBlock.classList.remove('casinoBankingAndPayoutsWidget__items-hidden--active');
					} else {
						hiddenBlock.classList.add('casinoBankingAndPayoutsWidget__items-hidden--active');
						visibleBlock.remove();
						el.remove();
					}
				})
			})
		}
	}
}

const casinoBankingAndPayoutsWidget = new CasinoBankingAndPayoutsWidget;

document.addEventListener('DOMContentLoaded', () => {
	casinoBankingAndPayoutsWidget.init();
})



import {
    changeCountry,
    getSelectedCountryList,
    updateAvatar,
    logout,
    setNotifications
} from "authApi";
import {utmParams as utmParamsProfile} from "globals";

class ProfileWidget {

    async generateCountryOfResidencyPopup() {
        let html = `
            <div class="residency_popup" id="residencyPopup">
              <div class="residency_popup-box">
                   <div class="title">
                      <span>Country of residency</span>
                      <svg id="residencyPopupCloseButton" class="close_popup" width="44" height="44" viewBox="0 0 44 44" fill="none" xmlns="http://www.w3.org/2000/svg">
                          <g clip-path="url(#clip0_8573_2932)">
                          <path d="M21.9968 20.5862L26.9468 15.6362L28.3608 17.0502L23.4108 22.0002L28.3608 26.9502L26.9468 28.3642L21.9968 23.4142L17.0468 28.3642L15.6328 26.9502L20.5828 22.0002L15.6328 17.0502L17.0468 15.6362L21.9968 20.5862Z" fill="white"/>
                          </g>
                          <rect x="0.5" y="0.5" width="43" height="43" rx="11.5" stroke="#6C6C6C" stroke-opacity="0.7"/>
                          <defs>
                          <clipPath id="clip0_8573_2932">
                          <rect width="24" height="24" fill="white" transform="translate(10 10)"/>
                          </clipPath>
                          </defs>
                      </svg>
                  </div>
                  <div class="search">
                    <div class="search_box">
                      <svg class="icon_search" width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                          <path d="M17.994 15.6715L22 19.6765L20.6765 21L16.6715 16.994C15.1813 18.1887 13.3278 18.8384 11.4178 18.8357C6.77119 18.8357 3 15.0645 3 10.4178C3 5.77119 6.77119 2 11.4178 2C16.0645 2 19.8357 5.77119 19.8357 10.4178C19.8384 12.3278 19.1887 14.1813 17.994 15.6715ZM16.1178 14.9775C17.3048 13.7568 17.9677 12.1205 17.965 10.4178C17.965 6.80004 15.0347 3.87063 11.4178 3.87063C7.80004 3.87063 4.87063 6.80004 4.87063 10.4178C4.87063 14.0347 7.80004 16.965 11.4178 16.965C13.1205 16.9677 14.7568 16.3048 15.9775 15.1178L16.1178 14.9775Z"
                                fill="#fff"/>
                      </svg>
                      <input id="residencyPopupSearch" placeholder="Search" class="search_input"/>
                    </div>
                  </div>
                  
                  <div class="countries_box" id="countryPopupBox">
                    <div class="loader-box">
                        <div class="loader">
                            <div></div>
                            <div></div>
                            <div></div>
                            <div></div>
                         </div>
                    </div>    
                  </div>
                  <div class="bottom_box">
                    <button id="residencyPopupSaveButton" class="save_button">
                      Save
                    </button>
                    <input type="hidden" id="residencyPopupCountryIdHidden"/>
                  </div>
              </div>
            </div>
            <div id="residencyPopupBackground" class="residency_popup-bg"></div>
        `;

        document.body.insertAdjacentHTML('beforeend', html);

        const residencyPopup = document.getElementById('residencyPopup');
        const countryPopupBox = document.getElementById('countryPopupBox');
        const residencyPopupBackground = document.getElementById('residencyPopupBackground');
        const residencyPopupCloseButton = document.getElementById('residencyPopupCloseButton');
        const residencyPopupSaveButton = document.getElementById('residencyPopupSaveButton');
        const residencyPopupSearch = document.getElementById('residencyPopupSearch');

        let countries = await getSelectedCountryList();

        this.appendCountriesFromQuery(
            countryPopupBox,
            countries
        );

        this.search(
            residencyPopupSearch,
            countries,
            countryPopupBox
        );

        this.closeElementClick([
                residencyPopup,
                residencyPopupBackground,
            ],
            residencyPopupCloseButton
        );

        this.setChangeCountryQueryClick(
            residencyPopupSaveButton,
            countryPopupBox,
            residencyPopup,
            residencyPopupBackground
        );
    }

    generateAvatarPopup() {
        const profileAvatarCurrentSrc = document.getElementById('profileAvatarCurrent').src;

        let html = `
            <div class="avatar_popup" id="avatarPopup">
              <div class="avatar_popup-box-full">           
                   <button class="avatar_popup-close" id="avatarClose">
                        <svg width="50" height="50" viewBox="0 0 50 50" fill="none" xmlns="http://www.w3.org/2000/svg">
                            <g clip-path="url(#clip0_7547_133184)">
                            <path d="M25.0028 23.3504L30.7778 17.5754L32.4275 19.2251L26.6525 25.0001L32.4275 30.7751L30.7778 32.4248L25.0028 26.6498L19.2278 32.4248L17.5781 30.7751L23.3531 25.0001L17.5781 19.2251L19.2278 17.5754L25.0028 23.3504Z" fill="white"/>
                            </g>
                            <rect x="0.5" y="0.5" width="49" height="49" rx="11.5" stroke="white" stroke-opacity="0.4"/>
                            <defs>
                            <clipPath id="clip0_7547_133184">
                            <rect width="28" height="28" fill="white" transform="translate(11 11)"/>
                            </clipPath>
                            </defs>
                        </svg>
                   </button>
                    
                   <div class="form">
                        <h2 class="title">Choose profile picture</h2>  
                        <p class="text">Choose a picture that represents you</p>
                        <div class="avatar_popup-image">
                            <img class="image" src="${profileAvatarCurrentSrc !== '/cdn/profile/avatars/empty.png' ? profileAvatarCurrentSrc : '/cdn/profile/avatars/empty.png'}" id="avatarSelectedImageBox"/>
                        </div> 
                        <div class="avatar_popup-select">
                            <img class="image auth_popup-avatar" alt="Casinos Analyzer" src="/cdn/profile/avatars/empty.png"/>
                            <img class="image auth_popup-avatar" alt="Casinos Analyzer" src="/cdn/profile/avatars/cleo.png"/>
                            <img class="image auth_popup-avatar" alt="Casinos Analyzer" src="/cdn/profile/avatars/joker.png"/>
                            <img class="image auth_popup-avatar" alt="Casinos Analyzer" src="/cdn/profile/avatars/king.png"/>
                            <img class="image auth_popup-avatar" alt="Casinos Analyzer" src="/cdn/profile/avatars/queen.png"/>
                            <img class="image auth_popup-avatar" alt="Casinos Analyzer" src="/cdn/profile/avatars/gorilla.png"/>
                            <img class="image auth_popup-avatar" alt="Casinos Analyzer" src="/cdn/profile/avatars/chip.png"/>
                            <img class="image auth_popup-avatar" alt="Casinos Analyzer" src="/cdn/profile/avatars/diamond.png"/>
                            <img class="image auth_popup-avatar" alt="Casinos Analyzer" src="/cdn/profile/avatars/dice.png"/>
                            <img class="image auth_popup-avatar" alt="Casinos Analyzer" src="/cdn/profile/avatars/roulette.png"/>
                            <img class="image auth_popup-avatar" alt="Casinos Analyzer" src="/cdn/profile/avatars/slots.png"/>
                        </div>
                        <input type="hidden" id="avatarHiddenSelect" value="empty"/>
                        <div class="bottom_box">
                            <button id="avatarSaveButton" class="save">Save</button>
                        </div>       
                </div>
              </div> 
            </div>
        `;

        document.body.insertAdjacentHTML('beforeend', html);

        this.selectAvatarClick(
            document.getElementsByClassName('auth_popup-avatar'),
            document.getElementById('avatarSelectedImageBox'),
            document.getElementById('avatarHiddenSelect'),
        );

        this.closeElementClick([
                document.getElementById('avatarPopup'),
            ],
            document.getElementById('avatarClose')
        );

        this.updateAvatarQuery(
            document.getElementById('avatarSaveButton')
        );
    }

    logoutClick() {
        const profileWidgetLogoutButtonElement = document.getElementById('profileWidgetLogoutButton');

        profileWidgetLogoutButtonElement ? profileWidgetLogoutButtonElement.addEventListener('click', async () => {
            let response = await logout();

            if (response['logout']) {
                window.location.href = storage.getReferringPageAfterLogout() ? storage.getReferringPageAfterLogout() : '/';
                storage.removeToken();
            }
        }) : null;
    }

    openCountryPopupClick() {
        const residencyPopupOpenButton = document.getElementById('residencyPopupOpenButton');

        residencyPopupOpenButton && residencyPopupOpenButton.addEventListener('click', () => {
            this.generateCountryOfResidencyPopup();
        });
    }

    openAvatarPopupClick() {
        const profileAvatar = document.getElementsByClassName('profileAvatar');

        Array.from(profileAvatar).forEach(el => {
            el.addEventListener('click', () => {
                this.generateAvatarPopup();
            });
        })
    }

    approvedUserNoRecaptchaLocalStorage() {
        if (!storage.getLoginOneTime()) {
            return storage.setLoginOneTime('yes');
        }
    }

    /**
     *
     * @param element
     * @param mainBox
     * @param hidden
     */
    selectAvatarClick(element, mainBox, hidden) {
        Array.from(element).forEach((el) => {
            el.addEventListener('click', () => {
                mainBox.src = el.src;

                hidden.value = this.extractAvatarName(el.src);
            })
        });
    }

    /**
     *
     * @param imageSrc
     * @returns {*}
     */
    extractAvatarName(imageSrc) {
        let parts = imageSrc.split('/');
        let filename = parts[parts.length - 1];

        return filename.split('.')[0];
    }

    /**
     *
     * @param element
     * @param countries
     * @param appendTo
     */
    search(element, countries, appendTo) {
        let filteredCountries;

        element.addEventListener('input', () => {
            const searchTerm = element.value.toLowerCase();

            filteredCountries = {
                'countries': countries['countries'].filter(country => country.name.toLowerCase().includes(searchTerm)),
                'countryId': countries['countryId']
            }

            this.appendCountriesFromQuery(appendTo, filteredCountries);
        });
    }

    /**
     *
     * @param element
     * @param countries
     * @returns {Promise<void>}
     */
    async appendCountriesFromQuery(element, countries) {
        let html = '';

        for (let country of countries['countries']) {
            html += `
                <div data-id="${country['id']}" class="country ${country['id'] === countries['countryId'] ? 'active' : ''}">
                   ${country['alpha2'] ? `<img class="image" width="32" height="32" src="/build/img/flags/${country['alpha2'].toLowerCase()}.svg"/>` :
                `<img class="image" width="32" height="32" src="/build/img/flags/wk.svg"/>`}
                   
                   <span class="country_name">
                     ${country['name']}
                   </span>
                   <div class="selected">
                     <svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                         <path d="M9.74987 14.9417L19.4992 5L21 6.52916L9.74987 18L3 11.1177L4.49974 9.58855L9.74987 14.9417Z" fill="#05E98F"/>
                     </svg>
                   </div>
                </div>
            `;
        }

        element.innerHTML = html;

        this.setHiddenInputCountryId(
            document.getElementsByClassName('country'),
        );

        this.setElementsListClassActiveToggle(
            document.getElementsByClassName('country'),
        );
    }

    subscriptionsSaveLoader() {
        const profileNotificationsLoader = document.getElementById('profileNotificationsLoader');

        profileNotificationsLoader.style.display = 'flex';

        setTimeout(() => {
            profileNotificationsLoader.style.display = 'none';
        }, 1300);
    }

    /**
     *
     * @returns {Promise<void>}
     */
    async setSubscriptionsQueryChange() {
        const profilePromoSubscribe = document.getElementById('profilePromoSubscribe');
        const profileReleasesSubscribe = document.getElementById('profileReleasesSubscribe');

        Array.from([profilePromoSubscribe, profileReleasesSubscribe]).forEach(el => {
            el && el.addEventListener('change', async () => {
                let response = await setNotifications(
                    {
                        'promoSubscribe': profilePromoSubscribe.checked,
                        'releasesSubscribe': profileReleasesSubscribe.checked,
                    }
                );

                this.subscriptionsSaveLoader();

                if (response['subscribe']) {
                    this.successMessageGenerateHTML(
                        'Notifications has been updated'
                    );
                }
            });
        });
    }

    /**
     *
     * @param element
     */
    updateAvatarQuery(element) {
        element.addEventListener('click', async () => {
            let avatarName = document.getElementById('avatarHiddenSelect').value;
            let response = await updateAvatar(avatarName);

            if (response['avatarUpdate']) {
                this.successMessageGenerateHTML(
                    'Profile picture is saved'
                );
                setTimeout(() => location.reload(), 1200);
            }
        });
    }

    /**
     *
     * @param message
     */
    successMessageGenerateHTML(message) {
        let html = `
            <div class="success" id="changeSuccessMessage">
                <div class="success_box">
                    <svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                        <path d="M12 22C6.477 22 2 17.523 2 12C2 6.477 6.477 2 12 2C17.523 2 22 6.477 22 12C22 17.523 17.523 22 12 22ZM12 20C14.1217 20 16.1566 19.1571 17.6569 17.6569C19.1571 16.1566 20 14.1217 20 12C20 9.87827 19.1571 7.84344 17.6569 6.34315C16.1566 4.84286 14.1217 4 12 4C9.87827 4 7.84344 4.84286 6.34315 6.34315C4.84285 7.84344 4 9.87827 4 12C4 14.1217 4.84285 16.1566 6.34314 17.6569C7.84344 19.1571 9.87827 20 12 20ZM11.003 16L6.76 11.757L8.174 10.343L11.003 13.172L16.659 7.515L18.074 8.929L11.003 16Z" fill="white"/>
                    </svg>
                    <p class="text">${message}</p>
                </div>
            </div>
        `;

        document.body.insertAdjacentHTML('beforeend', html);

        const changeSuccessMessage = document.getElementById('changeSuccessMessage');
        changeSuccessMessage.style.animation = 'show 0.5s forwards ease-in-out';

        this.hideSuccessMessage(changeSuccessMessage);
    }

    /**
     *
     * @param element
     */
    hideSuccessMessage(element) {
        setTimeout(() => {
            element.remove();
        }, 2000);
    }

    /**
     *
     * @param elements
     */
    setHiddenInputCountryId(elements) {
        const residencyPopupCountryIdHidden = document.getElementById('residencyPopupCountryIdHidden');

        Array.from(elements).forEach(el => {
            el.addEventListener('click', () => {
                residencyPopupCountryIdHidden.value = el.dataset.id;
            });
        });
    }

    /**
     *
     * @param saveButton
     * @param countryPopupBox
     * @param residencyPopup
     * @param residencyPopupBackground
     */
    setChangeCountryQueryClick(saveButton, countryPopupBox, residencyPopup, residencyPopupBackground) {
        const residencyPopupCountryIdHidden = document.getElementById('residencyPopupCountryIdHidden');

        saveButton.addEventListener('click', async () => {
            let response = await changeCountry(residencyPopupCountryIdHidden.value);

            if (response['changeCountry']) {
                this.successMessageGenerateHTML(
                    'Country has been updated'
                );
                this.saveLoader(
                    countryPopupBox,
                    residencyPopup,
                    residencyPopupBackground
                );
            }
        });
    }

    /**
     *
     * @param countryPopupBox
     * @param residencyPopup
     * @param residencyPopupBackground
     */
    saveLoader(countryPopupBox, residencyPopup, residencyPopupBackground) {
        countryPopupBox.style.opacity = 0.5;

        setTimeout(() => {
            countryPopupBox.style.opacity = 1;
            this.closePopup([
                residencyPopup,
                residencyPopupBackground
            ]);
        }, 1200);
    }

    /**
     *
     * @param elements
     */
    closePopup(elements) {
        Array.from(elements).forEach(el => {
            el.remove();
        });
    }

    /**
     *
     * @param elements
     */
    setElementsListClassActiveToggle(elements) {
        Array.from(elements).forEach(el => {
            el.addEventListener('click', () => {
                Array.from(elements).forEach(el => {
                    el.classList.remove('active');
                });
                el.classList.add('active');
            });
        })
    }

    /**
     *
     * @param elements
     * @param close
     */
    closeElementClick(elements, close) {
        Array.from(elements).forEach(el => {
            close.addEventListener('click', () => {
                el.remove();
            });
        });
    }

    setAmplitudeGamificationParams = (event, event_cat, event_name) => {
        const eventID = ["p_bonus_spin_n", "p_bonus_amount", "p_bonus_casino", "p_bonus_category", "p_bonus_country", "p_bonus_percent", "p_casino_category", "p_casino_city", "p_casino_country", "p_casino_state_usa", "p_casino_currency", "p_casino_deposit_low", "p_casino_payment", "p_casino", "p_casino_slot_soft", "p_game_category", "p_slot_category", "p_slot", "p_slot_payline", "p_blog_category", "p_blog_article", "p_website_category", "p_similar_casinos", "p_software_bonuses", "p_website_page", "p_home", "p_profile_rewards", "p_profile_shop", "p_other"];

        const ROUTE = document.body.dataset.routeBonus;
        const ROUTE__EXIST = eventID.findIndex(item => item === ROUTE);
        const EVENT__CAT = ROUTE__EXIST > -1 ? eventID[ROUTE__EXIST] : eventID[eventID.length - 1];

        const eventParams = {
            "page_url": JSON.stringify(document.location.origin + document.location.pathname),
            "page_current_path": JSON.stringify(document.location.pathname),
            "page_group": JSON.stringify(EVENT__CAT),
            "website_domain": JSON.stringify(document.location.hostname),
            "website_country": JSON.stringify(document.body.dataset.geo),
        }

        dataLayer.push(Object.assign({
            'event': `addEvents_${event}`,
            'event_id': `d-v1-e1`,
            'event_cat': event_cat,
            'event_name': event_name,
        }, eventParams, utmParamsProfile()));
    }

    amplitudeGamification(){
        const profileMenuRewards = document.querySelector(`[data-element="profile__menu--rewards"]`);
        if(profileMenuRewards){
            profileMenuRewards.addEventListener(`click`, () => {
                this.setAmplitudeGamificationParams(`click`, `p_profile_rewards`, `open`);
            })
        }

        const profileMenuReviews = document.querySelector(`[data-element="profile__menu--reviews"]`);
        if(profileMenuReviews){
            profileMenuReviews.addEventListener(`click`, () => {
                this.setAmplitudeGamificationParams(`click`, `p_profile_reviews`, `open`);
            })
        }
    }
}

const profileWidget = new ProfileWidget;

profileWidget.logoutClick();
profileWidget.openCountryPopupClick();
profileWidget.openAvatarPopupClick();
profileWidget.approvedUserNoRecaptchaLocalStorage();
profileWidget.setSubscriptionsQueryChange();
profileWidget.amplitudeGamification();


import {changePassword} from "/build/midori/assets/js/api/auth/authApi.js";

class PartnerChangePasswordWidget {

    constructor() {
        this.partnerNewPasswordInput = document.getElementById('partnerNewPasswordInput');
        this.partnerConfirmNewPasswordInput = document.getElementById('partnerConfirmNewPasswordInput');
        this.partnerChangePasswordSaveButton = document.getElementById('partnerChangePasswordSaveButton');
        this.partnerChangePasswordError = document.getElementById('partnerChangePasswordError');
        this.partnerChangePasswordConfirm = document.getElementById('partnerChangePasswordConfirm');
        this.partnerNewPasswordShow = document.getElementById('partnerNewPasswordShow');
        this.partnerNewPasswordConfirmShow = document.getElementById('partnerNewPasswordConfirmShow');
    }

    changePasswordClick() {
        this.partnerChangePasswordSaveButton.addEventListener('click', async () => {
            this.errorsClear();

            if (this.partnerNewPasswordInput.value === this.partnerConfirmNewPasswordInput.value) {
                let updatePasswordData = await changePassword(
                    this.partnerNewPasswordInput.value,
                );

                if (updatePasswordData['changePassword']) {
                    this.successMessageGenerateHTML();
                    this.errorsClear();

                    setTimeout(() => {
                        window.location.pathname = '/partner-profile';
                    }, 1200);
                }

                this.errorRequest(updatePasswordData);
            }
        });
    }

    successMessageGenerateHTML() {
        let html = `
            <div class="success" id="passwordChangeSuccessMessage">
                <div class="success_box">
                    <svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                        <path d="M12 22C6.477 22 2 17.523 2 12C2 6.477 6.477 2 12 2C17.523 2 22 6.477 22 12C22 17.523 17.523 22 12 22ZM12 20C14.1217 20 16.1566 19.1571 17.6569 17.6569C19.1571 16.1566 20 14.1217 20 12C20 9.87827 19.1571 7.84344 17.6569 6.34315C16.1566 4.84286 14.1217 4 12 4C9.87827 4 7.84344 4.84286 6.34315 6.34315C4.84285 7.84344 4 9.87827 4 12C4 14.1217 4.84285 16.1566 6.34314 17.6569C7.84344 19.1571 9.87827 20 12 20ZM11.003 16L6.76 11.757L8.174 10.343L11.003 13.172L16.659 7.515L18.074 8.929L11.003 16Z" fill="white"/>
                    </svg>
                    <p class="text">Password was updated</p>
                </div>
            </div>
        `;

        document.body.insertAdjacentHTML('beforeend', html);

        const passwordChangeSuccessMessage = document.getElementById('passwordChangeSuccessMessage');

        passwordChangeSuccessMessage.style.animation = 'show 0.5s forwards ease-in-out';

        this.hideSuccessMessage(
            passwordChangeSuccessMessage
        );
    }

    errorsClear() {
        this.partnerChangePasswordError.innerHTML = '';
    }

    showPassword() {
        this.partnerNewPasswordShow.addEventListener('click', () => {
            if (this.partnerNewPasswordInput.type === 'password') {
                this.partnerNewPasswordInput.type = 'text';
            } else {
                this.partnerNewPasswordInput.type = 'password';
            }
        });

        this.partnerNewPasswordConfirmShow.addEventListener('click', () => {
            if (this.partnerConfirmNewPasswordInput.type === 'password') {
                this.partnerConfirmNewPasswordInput.type = 'text';
            } else {
                this.partnerConfirmNewPasswordInput.type = 'password';
            }
        });
    }

    /**
     *
     * @returns {this is HTMLElement[]}
     */
    confirmPasswordInput() {
        const partnerNewPasswordInput = this.partnerNewPasswordInput;
        const partnerConfirmNewPasswordInput = this.partnerConfirmNewPasswordInput;

        const inputElements = [partnerNewPasswordInput, partnerConfirmNewPasswordInput];

        inputElements.forEach(el => {
            el.addEventListener('input', () => {
                if (partnerNewPasswordInput.value !== partnerConfirmNewPasswordInput.value) {
                    this.partnerChangePasswordConfirm.innerHTML = 'Password is not the same';
                } else {
                    this.partnerChangePasswordConfirm.innerHTML = '';
                }
            });
        });
    }

    /**
     *
     * @param element
     */
    hideSuccessMessage(element) {
        setTimeout(() => {
            element.remove();
        }, 2000);
    }

    /**
     *
     * @param error
     */
    errorRequest(error) {
        if (Object.keys(error['errors']).length) {
            this.partnerChangePasswordError.innerHTML = error['errors']['password'] ?? '';
        }
    }

    generate() {
        this.changePasswordClick();
        this.showPassword();
        this.confirmPasswordInput();
    }
}

const partnerChangePasswordWidget = new PartnerChangePasswordWidget;

partnerChangePasswordWidget.generate();


import {logout} from "/build/midori/assets/js/api/auth/authApi.js";
import {deleteCookie} from "/build/midori/assets/js/globals.js";

class PartnerAccountWidget {

    constructor() {
        this.partnerProfileWidgetLogoutButton = document.getElementById('partnerProfileWidgetLogoutButton');
    }

    logoutClick() {
        this.partnerProfileWidgetLogoutButton ? this.partnerProfileWidgetLogoutButton.addEventListener('click', async () => {
            let response = await logout();

            if (response['logout']) {
                window.location.href = '/';
                deleteCookie('token');
            }
        }) : null;
    }

    generate() {
        this.logoutClick();
    }
}

const partnerAccountWidget = new PartnerAccountWidget;

partnerAccountWidget.generate();

class PartnerProfileWidget {

    constructor() {
        this.partnerProfileDropdownCasino = document.getElementById('partnerProfileDropdownCasino');
        this.partnerProfileOpenDropdownCasino = document.getElementById('partnerProfileOpenDropdownCasino');
        this.partnerProfileDropdownButtonCasino = document.getElementById('partnerProfileDropdownButtonCasino');
    }

    /**
     *
     * @param button
     * @param dropdown
     * @param icon
     */
    dropdownClick(button, dropdown, icon) {
        dropdown.style.display = 'none';

        button.addEventListener('click', () => {
            if (dropdown.style.display === 'none') {
                dropdown.style.display = 'block';
                icon.style.rotate = '180deg';
            } else {
                dropdown.style.display = 'none';
                icon.style.rotate = '0deg';
            }
        });
    }

    generate() {
        this.dropdownClick(
            this.partnerProfileOpenDropdownCasino,
            this.partnerProfileDropdownCasino,
            this.partnerProfileDropdownButtonCasino
        );
    }
}

const partnerProfileWidget = new PartnerProfileWidget;

partnerProfileWidget.generate();

import {getUserReviewPaginated, read} from "/build/midori/assets/js/api/userReview/userReviewApi.js";
import {__translate as __cucw_translate} from "translate";
import {getLocaleCountry as __cucw_localeCountry} from "globals";

class PartnerReviewsWidget {

    constructor() {
        this.sortType = 'newest';
        this.showMorePage = 1;
        this.commentTextOutput = document.querySelectorAll('.comment_text-output');
        this.commentReplyOutput = document.querySelectorAll('.reply_text-output');
        this.partnerReviewsCount = document.getElementById('partnerReviewsCount');
        this.partnerReviewsReplyButtons = document.getElementsByClassName('button_reply');
        this.partnerReviewsReplyBox = document.getElementsByClassName('casino_reply-box');
        this.casinoUserCommentAppendBox = document.getElementById('casinoUserCommentAppendBox');
        this.casinoUserCommentPreloader = document.getElementById('casinoUserCommentPreloader');
    }

    /**
     *
     * @param rating
     * @returns {string}
     */
    generateStars(rating) {
        const filledStars = Math.floor(rating);
        const halfStar = rating - filledStars >= 0.5;
        const emptyStars = 5 - (filledStars + (halfStar ? 1 : 0));

        const decimalPart = rating.toFixed(2);
        const tenthsPlace = decimalPart.slice(-2, -1);

        let emptyStarsRoundedNumber;

        if (parseInt(tenthsPlace) >= 5) {
            emptyStarsRoundedNumber = Math.floor(emptyStars);
        } else {
            emptyStarsRoundedNumber = Math.ceil(emptyStars);
        }

        let starsHtml = '';

        for (let i = 0; i < filledStars; i++) {
            starsHtml += `
              <svg class="icon_star-review" width="32" height="32" viewBox="0 0 32 32" fill="none" xmlns="http://www.w3.org/2000/svg">
                  <path d="M15.3333 5.3335L18.9056 12.2606L26.6667 13.4821L21.1133 18.9848L22.3377 26.6668L15.3333 23.1406L8.32895 26.6668L9.55333 18.9848L4 13.4821L11.7611 12.2606L15.3333 5.3335Z" fill="#ffd700"></path>
                  <path fill-rule="evenodd" clip-rule="evenodd" d="M16 4C16.4047 4 16.7751 4.23745 16.9591 4.61469L20.1531 11.1651L27.0923 12.3202C27.492 12.3868 27.8222 12.6822 27.9473 13.085C28.0723 13.4878 27.971 13.9299 27.6851 14.2296L22.7198 19.4331L23.8145 26.6975C23.8776 27.1158 23.7112 27.5358 23.3838 27.7848C23.0564 28.0337 22.6234 28.0695 22.2627 27.8775L16 24.543L9.7373 27.8775C9.37663 28.0695 8.94355 28.0337 8.61618 27.7848C8.28881 27.5358 8.12243 27.1158 8.18548 26.6975L9.28021 19.4331L4.31491 14.2296C4.02897 13.9299 3.92768 13.4878 4.05273 13.085C4.17777 12.6822 4.50803 12.3868 4.90766 12.3202L11.8469 11.1651L15.0409 4.61469C15.2249 4.23745 15.5953 4 16 4ZM16 7.60619L13.5161 12.7003C13.3597 13.0212 13.0661 13.2445 12.7262 13.301L7.32961 14.1993L11.191 18.246C11.4342 18.5009 11.5464 18.8621 11.4928 19.218L10.6414 24.8673L15.5118 22.2741C15.8186 22.1108 16.1814 22.1108 16.4882 22.2741L21.3586 24.8673L20.5072 19.218C20.4536 18.8621 20.5658 18.5009 20.809 18.246L24.6704 14.1993L19.2738 13.301C18.9339 13.2445 18.6403 13.0212 18.4839 12.7003L16 7.60619Z" fill="#ffd700"></path>
              </svg>
            `;
        }

        if (halfStar) {
            starsHtml += `
              <svg class="icon_star-review-half" width="32" height="32" viewBox="0 0 32 32" fill="none" xmlns="http://www.w3.org/2000/svg">
                <mask id="mask0_101_8" style="mask-type:alpha" maskUnits="userSpaceOnUse" x="4" y="4" width="24" height="24">
                    <path d="M15.3333 5.33333L18.9056 12.2604L26.6667 13.4819L21.1133 18.9846L22.3377 26.6667L15.3333 23.1404L8.32895 26.6667L9.55333 18.9846L4 13.4819L11.7611 12.2604L15.3333 5.33333Z" fill="#F0D800"></path>
                    <path fill-rule="evenodd" clip-rule="evenodd" d="M16 4C16.4047 4 16.7751 4.23745 16.9591 4.61469L20.1531 11.1651L27.0923 12.3202C27.492 12.3868 27.8222 12.6822 27.9473 13.085C28.0723 13.4878 27.971 13.9299 27.6851 14.2296L22.7198 19.4331L23.8145 26.6975C23.8776 27.1158 23.7112 27.5358 23.3838 27.7848C23.0564 28.0337 22.6234 28.0695 22.2627 27.8775L16 24.543L9.7373 27.8775C9.37663 28.0695 8.94355 28.0337 8.61618 27.7848C8.28881 27.5358 8.12243 27.1158 8.18548 26.6975L9.28021 19.4331L4.31491 14.2296C4.02897 13.9299 3.92768 13.4878 4.05273 13.085C4.17777 12.6822 4.50803 12.3868 4.90766 12.3202L11.8469 11.1651L15.0409 4.61469C15.2249 4.23745 15.5953 4 16 4ZM16 7.60619L13.5161 12.7003C13.3597 13.0212 13.0661 13.2445 12.7262 13.301L7.32961 14.1993L11.191 18.246C11.4342 18.5009 11.5464 18.8621 11.4928 19.218L10.6414 24.8673L15.5118 22.2741C15.8186 22.1108 16.1814 22.1108 16.4882 22.2741L21.3586 24.8673L20.5072 19.218C20.4536 18.8621 20.5658 18.5009 20.809 18.246L24.6704 14.1993L19.2738 13.301C18.9339 13.2445 18.6403 13.0212 18.4839 12.7003L16 7.60619Z" fill="#F0D800"></path>
                </mask>
                <g mask="url(#mask0_101_8)">
                    <rect x="3" y="4" width="13" height="26" fill="#F0D800"></rect>
                    <rect x="16" y="3" width="19" height="27" fill="#D9D9D9"></rect>
                </g>
              </svg>
            `;
        }

        for (let i = 0; i < emptyStarsRoundedNumber; i++) {
            starsHtml += `
              <svg class="icon_star-review" width="32" height="32" viewBox="0 0 32 32" fill="none" xmlns="http://www.w3.org/2000/svg">
                 <path d="M15.3333 5.3335L18.9056 12.2606L26.6667 13.4821L21.1133 18.9848L22.3377 26.6668L15.3333 23.1406L8.32895 26.6668L9.55333 18.9848L4 13.4821L11.7611 12.2606L15.3333 5.3335Z" fill="#d9d9d9"></path>
                 <path fill-rule="evenodd" clip-rule="evenodd" d="M16 4C16.4047 4 16.7751 4.23745 16.9591 4.61469L20.1531 11.1651L27.0923 12.3202C27.492 12.3868 27.8222 12.6822 27.9473 13.085C28.0723 13.4878 27.971 13.9299 27.6851 14.2296L22.7198 19.4331L23.8145 26.6975C23.8776 27.1158 23.7112 27.5358 23.3838 27.7848C23.0564 28.0337 22.6234 28.0695 22.2627 27.8775L16 24.543L9.7373 27.8775C9.37663 28.0695 8.94355 28.0337 8.61618 27.7848C8.28881 27.5358 8.12243 27.1158 8.18548 26.6975L9.28021 19.4331L4.31491 14.2296C4.02897 13.9299 3.92768 13.4878 4.05273 13.085C4.17777 12.6822 4.50803 12.3868 4.90766 12.3202L11.8469 11.1651L15.0409 4.61469C15.2249 4.23745 15.5953 4 16 4ZM16 7.60619L13.5161 12.7003C13.3597 13.0212 13.0661 13.2445 12.7262 13.301L7.32961 14.1993L11.191 18.246C11.4342 18.5009 11.5464 18.8621 11.4928 19.218L10.6414 24.8673L15.5118 22.2741C15.8186 22.1108 16.1814 22.1108 16.4882 22.2741L21.3586 24.8673L20.5072 19.218C20.4536 18.8621 20.5658 18.5009 20.809 18.246L24.6704 14.1993L19.2738 13.301C18.9339 13.2445 18.6403 13.0212 18.4839 12.7003L16 7.60619Z" fill="#d9d9d9"></path>
              </svg>
            `;
        }

        return starsHtml;
    }

    /**
     *
     * @param elements
     */
    addTextShowMore(elements) {
        elements.forEach(element => {
            if (element.innerText.length > 200) {
                const truncatedText = element.innerText.slice(0, 200);
                const remainingText = element.innerText.slice(200);

                const hiddenText = document.createElement('span');
                hiddenText.classList.add('hidden_text');
                hiddenText.innerText = truncatedText;

                const showMoreBtn = document.createElement('button');
                showMoreBtn.classList.add('show_more-btn');
                showMoreBtn.innerText = `${__cucw_translate('Show more', __cucw_localeCountry()) ?? 'Show more'}`;

                showMoreBtn.addEventListener('click', () => {
                    if (hiddenText.innerText === truncatedText) {
                        hiddenText.innerText = truncatedText + remainingText;
                        showMoreBtn.innerText = `${__cucw_translate('Show less', __cucw_localeCountry()) ?? 'Show less'}`;
                        showMoreBtn.classList.add('show_less');
                    } else {
                        hiddenText.innerText = truncatedText;
                        showMoreBtn.innerText = `${__cucw_translate('Show more', __cucw_localeCountry()) ?? 'Show more'}`;
                        showMoreBtn.classList.remove('show_less');
                    }
                });

                element.innerHTML = '';
                element.appendChild(hiddenText);
                element.appendChild(showMoreBtn);
            }
        });
    }

    /**
     *
     * @param inputDateStr
     * @returns {string}
     */
    dateConvert(inputDateStr) {
        const inputDate = new Date(inputDateStr);

        const months = [
            'January',
            'February',
            'March',
            'April',
            'May',
            'June',
            'July',
            'August',
            'September',
            'October',
            'November',
            'December'
        ];

        const day = inputDate.getDate();
        const month = months[inputDate.getMonth()];
        const year = inputDate.getFullYear();

        return `${day} ${month}, ${year}`;
    }

    changeCasinoTab() {
        window.addEventListener('partnerLeftBarEvent', async (event) => {
            this.showMorePage = 1;

            let data = await this.getReviewsQuery(event.detail.casinoId);

            this.appendReviews(
                data,
                event.detail.casinoId,
                true
            ).then();
        });
    }

    addReplyClick() {
        Array.from(this.partnerReviewsReplyButtons).forEach((el, index) => {
            el.addEventListener('click', () => {
                this.partnerReviewsReplyBox[index].style.display = 'block';
                el.style.display = 'none';
            });
        });
    }

    /**
     *
     * @param casinoId
     * @returns {Promise<*>}
     */
    async getReviewsQuery(casinoId) {
        return await getUserReviewPaginated(
            this.sortType,
            casinoId,
            this.showMorePage
        );
    }

    /**
     *
     * @param data
     * @param casinoId
     * @param isChangedTab
     * @returns {Promise<void>}
     */
    async appendReviews(data, casinoId, isChangedTab) {
        this.partnerReviewsCount.innerText = `(${data['userReviews'].length})`;
        this.casinoUserCommentPreloader ? this.casinoUserCommentPreloader.remove() : null;

        isChangedTab ? this.casinoUserCommentAppendBox.innerHTML = '' : null;

        data['userReviews'] ? Array.from(data['userReviews']).forEach((data, index) => {
            document.getElementById('casinoNoReviewsText') ? document.getElementById('casinoNoReviewsText').remove() : null;

            this.casinoUserCommentAppendBox.innerHTML += `
                <div class="casinoUserComment_item ${index > 4 ? 'casinoUserComment_item-hidden' : 'casinoUserComment_item-fadeIn'} ${!data['is_read'] ? 'new' : ''}" data-user-review-id=${data['id']}>
                    <div class="casinoUserComment_item-info">
                        ${!data['is_read'] ? '<div class="new_label">new</div>' : ''}
                        <div class="user">
                            <div class="avatar"
                                 style="background-image: url(${data['avatar']});"></div>
                            <div class="info">
                                <div class="base_info">
                                    <p class="username">${data['username']}</p>
                                        ${data['alpha2'] ? `
                                        <div class="flag"
                                             style="background-image: url('/build/img/flags/${data['alpha2'].toLowerCase() + '.svg'}');"></div>
                                        ` : ''}                               
                                </div>
                                <span class="reviews">${data['user_review_count']} reviews</span>
                            </div>
                        </div>
                        <div class="reviews_total">
                            <div class="stars_box">
                                <div class="stars_box-counter">
                                    ${this.generateStars(parseFloat(data['score']))}
                                </div>
                                <span class="stars_box-total">
                                ${data['score']}
                            </span>
                            </div>
                            <p class="date">${this.dateConvert(data['created'])}</p>
                        </div>
                    </div>
                    <div class="casinoUserComment_item-info">
                        <div class="comment">
                            <p class="text comment_text-output">${data['comment']}</p>
                            ${data['pros'] ? `
                               <div class="pros_cons">
                                  <p class="title title_pros">Pros:</p>
                                  <p class="text pros_text-output">
                                      ${data['pros']}
                                  </p>
                               </div>
                            ` : ''}
                          
                            ${data['cons'] ? `
                               <div class="pros_cons">
                                  <p class="title title_cons">Pros:</p>
                                  <p class="text pros_text-output">
                                      ${data['cons']}
                                  </p>
                               </div>
                            ` : ''}
                        </div>
    
                        <div class="detailed_score">
                            <div class="option">
                                <p class="title">Promotions & Bonuses</p>
                                <span class="value">${data['detailed_score']['promotions_and_bonuses']}</span>
                            </div>
                            <div class="option">
                                <p class="title">Deposits & Withdrawals</p>
                                <span class="value">${data['detailed_score']['deposits_and_withdrawals']}</span>
                            </div>
                            <div class="option">
                                <p class="title">Games Variety</p>
                                <span class="value">${data['detailed_score']['games_variety']}</span>
                            </div>
                            <div class="option">
                                <p class="title">Support</p>
                                <span class="value">${data['detailed_score']['support']}</span>
                            </div>
                            <div class="option">
                                <p class="title">Website convenience</p>
                                <span class="value">${data['detailed_score']['website_convenience']}</span>
                            </div>
                        </div>
                    </div>
                    <div class="casinoUserComment_item-info last_info">
                       <p class="helpful helpfulUnlike_click" data-like="${data['likes']}">
                               <svg class="icon_helpful" width="20" height="20" viewBox="0 0 20 20" fill="none" xmlns="http://www.w3.org/2000/svg">
                                   <g opacity="0.3" clip-path="url(#clip0_9630_89675)">
                                       <path d="M1.66927 7.49997H4.16927V17.5H1.66927C1.44826 17.5 1.2363 17.4122 1.08002 17.2559C0.923735 17.0996 0.835938 16.8877 0.835938 16.6666V8.3333C0.835937 8.11229 0.923735 7.90033 1.08002 7.74405C1.2363 7.58777 1.44826 7.49997 1.66927 7.49997ZM6.0801 6.42247L11.4134 1.08914C11.4843 1.01805 11.5785 0.974943 11.6786 0.967747C11.7788 0.960551 11.8781 0.989749 11.9584 1.04997L12.6693 1.5833C12.8667 1.73151 13.0158 1.93485 13.0978 2.16768C13.1798 2.40052 13.1911 2.65243 13.1301 2.89164L12.1693 6.66664H17.5026C17.9446 6.66664 18.3686 6.84223 18.6811 7.15479C18.9937 7.46735 19.1693 7.89128 19.1693 8.3333V10.0866C19.1695 10.3044 19.127 10.5202 19.0443 10.7216L16.4651 16.9841C16.4022 17.1368 16.2953 17.2674 16.1581 17.3592C16.0208 17.451 15.8594 17.5 15.6943 17.5H6.66927C6.44826 17.5 6.2363 17.4122 6.08002 17.2559C5.92374 17.0996 5.83594 16.8877 5.83594 16.6666V7.01164C5.83598 6.79064 5.92381 6.57871 6.0801 6.42247Z" fill="#4443b8"></path>
                                   </g>
                               </svg>
                               ${data['likes'] ? `<span class="helpful_count" data-like="${data['likes']}">${data['likes']}</span>` : `<span class="helpful_count" >0</span>`}    
                      </p>
                      <button class="button_reply">Reply</button>
                    </div>
                    <div class="casino_reply-box">
                        <label class="label">
                            Your reply
                            <textarea maxlength="3000" class="textarea"></textarea>
                        </label>
                        <div class="save_button-box">
                            <button class="save">Submit</button>
                        </div>
                    </div>
                </div>
            `;
        }) : this.casinoUserCommentAppendBox.innerHTML = `
            <p id="casinoNoReviewsText">There's no user review for your casino yet!</p>
        `;

        this.addReplyClick();

        await read(casinoId);

        this.casinoUserCommentAppendBox.innerHTML += `
            ${data['userReviews'].length >= 5 ?
            `<div class="casinoUserComment_showMore-container">
                    <button id="casinoUserCommentShowMoreButton" class="btn-show-more">${__cucw_translate('Show more', __cucw_localeCountry()) ?? 'Show more'}</button>
            </div>` : ''}`;

        data['userReviews'].length >= 5 ? this.showMorePage++ : null;

        this.addTextShowMore(document.querySelectorAll('.comment_text-output'));
        this.addTextShowMore(document.querySelectorAll('.reply_text-output'));

        this.showMoreItemsClick(
            document.getElementById('casinoUserCommentShowMoreButton'),
            casinoId
        );
    }

    /**
     *
     * @param button
     * @param casinoId
     */
    showMoreItemsClick(button, casinoId) {
        button ? button.addEventListener('click', async () => {
            button.remove();

            let data = await this.getReviewsQuery(casinoId)

            this.appendReviews(
                data,
                casinoId
            ).then();
        }) : null;
    }

    generate() {
        this.changeCasinoTab();
    }
}

let partnerReviewsWidget = new PartnerReviewsWidget();

partnerReviewsWidget.generate();

class PartnerLeftBarWidget {

    constructor() {
        this.currentCasinoLogo = document.querySelector('#partnerProfileOpenDropdownCasino .background');
        this.currentCasinoName = document.querySelector('#partnerProfileOpenDropdownCasino .name');

        this.casinoItems = document.querySelectorAll('.current_casino-dropdown .casinos .item');
        this.partnerProfileDropdownCasino = document.getElementById('partnerProfileDropdownCasino');
        this.partnerProfileOpenDropdownCasino = document.getElementById('partnerProfileOpenDropdownCasino');
        this.partnerProfileDropdownButtonCasino = document.getElementById('partnerProfileDropdownButtonCasino');
    }

    /**
     *
     * @param button
     * @param dropdown
     * @param icon
     */
    dropdownClick(button, dropdown, icon) {
        dropdown ? dropdown.style.display = 'none' : null;

        button.addEventListener('click', () => {
            if (dropdown.style.display === 'none') {
                dropdown.style.display = 'block';
                icon.style.rotate = '180deg';
            } else {
                dropdown.style.display = 'none';
                icon.style.rotate = '0deg';
            }
        });
    }

    /**
     *
     * @param casinoId
     * @param changeItem
     */
    setCurrentCasino(casinoId, changeItem) {
        const casinoItemsArray = Array.from(this.casinoItems);

        const selectedCasino = casinoItemsArray.find(el => el.dataset.casinoId === casinoId);

        if (!selectedCasino) {
            return;
        }

        const currentCasino = {
            id: this.partnerProfileOpenDropdownCasino.dataset.casinoId,
            name: this.currentCasinoName.innerText,
            replyCount: this.partnerProfileOpenDropdownCasino.dataset.casinoReplyCount,
            logoSrc: this.currentCasinoLogo.src,
            logoBackground: getComputedStyle(this.currentCasinoLogo).background
        };

        this.updateCurrentCasinoUI(selectedCasino);

        this.updateSelectedCasinoItem(selectedCasino, currentCasino);

        if (changeItem) {
            storage.setPartnerCasinoId(casinoId);
        }
    }

    /**
     *
     * @param selectedCasino
     */
    updateCurrentCasinoUI(selectedCasino) {
        const selectedCasinoLogoBackground = getComputedStyle(selectedCasino.children[0]).background;

        this.currentCasinoLogo.setAttribute('src', selectedCasino.dataset.casinoLogo);
        this.currentCasinoLogo.setAttribute('style', `background: ${selectedCasinoLogoBackground}`);
        this.currentCasinoName.innerText = selectedCasino.dataset.casinoName;
        this.partnerProfileOpenDropdownCasino.dataset.casinoId = selectedCasino.dataset.casinoId;
        this.partnerProfileOpenDropdownCasino.dataset.casinoReplyCount = selectedCasino.dataset.casinoReplyCount;
    }

    /**
     *
     * @param selectedCasino
     * @param currentCasino
     */
    updateSelectedCasinoItem(selectedCasino, currentCasino) {
        const currentCasinoLogoBackground = currentCasino.logoBackground;

        selectedCasino.children[0].setAttribute('src', currentCasino.logoSrc);
        selectedCasino.children[0].setAttribute('style', `background: ${currentCasinoLogoBackground}`);
        selectedCasino.children[1].innerText = currentCasino.name;
        selectedCasino.children[2] ? selectedCasino.children[2].innerHTML = (currentCasino.replyCount > 0 ? `<p class="reply_value">${currentCasino.replyCount}</p>` : '') : null;

        selectedCasino.dataset.casinoName = currentCasino.name;
        selectedCasino.dataset.casinoLogo = currentCasino.logoSrc;
        selectedCasino.dataset.casinoId = currentCasino.id;
        selectedCasino.dataset.casinoReplyCount = currentCasino.replyCount;
    }

    changeSelectedCasinoClick() {
        Array.from(this.casinoItems).forEach(el => {
            el.addEventListener('click', () => {
                this.setCurrentCasino(
                    el.dataset.casinoId,
                    true
                );

                this.dispatchPartnerLeftBarEvent(
                    storage.getPartnerCasinoId() ? storage.getPartnerCasinoId() : el.dataset.casinoId
                );
            });
        })
    }

    selectedCasinoLoad() {
        let currentCasinoId = storage.getPartnerCasinoId() ? storage.getPartnerCasinoId() : this.partnerProfileOpenDropdownCasino.dataset.casinoId;

        this.dispatchPartnerLeftBarEvent(
            currentCasinoId
        );
    }

    /**
     *
     * @param casinoId
     */
    dispatchPartnerLeftBarEvent(casinoId) {
        const event = new CustomEvent('partnerLeftBarEvent', {
            detail: {
                casinoId: casinoId
            }
        });

        window.dispatchEvent(event);
    }

    generate() {
        this.selectedCasinoLoad();
        this.changeSelectedCasinoClick();

        this.dropdownClick(
            this.partnerProfileOpenDropdownCasino,
            this.partnerProfileDropdownCasino,
            this.partnerProfileDropdownButtonCasino
        );
        this.setCurrentCasino(
            storage.getPartnerCasinoId(),
            false
        );
    }
}

const partnerLeftBarWidget = new PartnerLeftBarWidget;

partnerLeftBarWidget.generate();

import {readReply} from "userReviewApi";
import {__translate as __mrw_translate} from "translate";
import {getLocaleCountry as __mrw_localeCountry} from "globals";

class MyReviewsWidget {

	constructor() {
		this.replyBodyOutput = document.querySelectorAll('.reply_body-output');
		this.userCommentOutput = document.querySelectorAll('.user_comment-output');
		this.commentProsOutput = document.querySelectorAll('.pros_text-output');
		this.commentConsOutput = document.querySelectorAll('.cons_text-output');
		this.newReplyBadge = document.querySelectorAll('.new_reply-badge');
	}

	async init() {
		if (this.newReplyBadge.length > 0) {
			await readReply();
		}

		this.addTextShowMore(this.replyBodyOutput);
		this.addTextShowMore(this.userCommentOutput);
	}

	/**
	 *
	 * @param elements
	 */
	addTextShowMore(elements) {
		elements.forEach(element => {
			if (element.innerText.length > 200) {
				const truncatedText = element.innerText.slice(0, 200);
				const remainingText = element.innerText.slice(200);

				const hiddenText = document.createElement('span');
				hiddenText.classList.add('hidden_text');
				hiddenText.innerText = truncatedText;

				const showMoreBtn = document.createElement('button');
				showMoreBtn.classList.add('show_more-btn');
				showMoreBtn.innerText = `${__mrw_translate('Show more', __mrw_localeCountry()) ?? 'Show more'}`;

				showMoreBtn.addEventListener('click', () => {
					if (hiddenText.innerText === truncatedText) {
						hiddenText.innerText = truncatedText + remainingText;
						showMoreBtn.innerText = `${__mrw_translate('Show less', __mrw_localeCountry()) ?? 'Show less'}`;
						showMoreBtn.classList.add('show_less');
					} else {
						hiddenText.innerText = truncatedText;
						showMoreBtn.innerText = `${__mrw_translate('Show more', __mrw_localeCountry()) ?? 'Show more'}`;
						showMoreBtn.classList.remove('show_less');
					}
				});

				element.innerHTML = '';
				element.appendChild(hiddenText);
				element.appendChild(showMoreBtn);
			}
		});
	}
}

const myReviewsWidget = new MyReviewsWidget;

myReviewsWidget.init().catch((e) => console.warn(e));


import {updateDetails} from "authApi";

class PersonalDetailsWidget {

	updateDetailsClick() {
		const authUsernameInputElement = document.getElementById('authUsernameInput');
		const personalDetailsWidgetSaveButtonElement = document.getElementById('personalDetailsWidgetSaveButton');

		personalDetailsWidgetSaveButtonElement.addEventListener('click', async () => {
			let updateDetailsData = await updateDetails(
				authUsernameInputElement.value
			);

			if (updateDetailsData['update']) {
				this.successMessageGenerateHTML();
				this.errorsClear();

				setTimeout(() => {
					window.location.pathname = '/profile';
				}, 1200);
			}

			this.errorRequest(updateDetailsData);
		});
	}

	successMessageGenerateHTML() {
		let html = `
            <div class="success" id="personalDetailsSuccessMessage">
                <div class="success_box">
                    <svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                        <path d="M12 22C6.477 22 2 17.523 2 12C2 6.477 6.477 2 12 2C17.523 2 22 6.477 22 12C22 17.523 17.523 22 12 22ZM12 20C14.1217 20 16.1566 19.1571 17.6569 17.6569C19.1571 16.1566 20 14.1217 20 12C20 9.87827 19.1571 7.84344 17.6569 6.34315C16.1566 4.84286 14.1217 4 12 4C9.87827 4 7.84344 4.84286 6.34315 6.34315C4.84285 7.84344 4 9.87827 4 12C4 14.1217 4.84285 16.1566 6.34314 17.6569C7.84344 19.1571 9.87827 20 12 20ZM11.003 16L6.76 11.757L8.174 10.343L11.003 13.172L16.659 7.515L18.074 8.929L11.003 16Z" fill="white"/>
                    </svg>
                    <p class="text">Details was updated</p>
                </div>
            </div>
        `;

		document.body.insertAdjacentHTML('beforeend', html);

		const personalDetailsSuccessMessageElement = document.getElementById('personalDetailsSuccessMessage');
		personalDetailsSuccessMessageElement.style.animation = 'show 0.5s forwards ease-in-out';

		this.hideSuccessMessage(personalDetailsSuccessMessageElement);
	}

	errorsClear() {
		const personalDetailsUsernameErrorElement = document.getElementById('personalDetailsUsernameError');

		personalDetailsUsernameErrorElement.innerHTML = '';
	}

	/**
	 *
	 * @param element
	 */
	hideSuccessMessage(element) {
		setTimeout(() => {
			element.remove();
		}, 2000);
	}

	/**
	 *
	 * @param error
	 */
	errorRequest(error) {
		const personalDetailsUsernameErrorElement = document.getElementById('personalDetailsUsernameError');

		if (Object.keys(error['errors']).length) {
			personalDetailsUsernameErrorElement.innerHTML = error['errors']['username'] ?? '';
		}
	}
}

const personalDetailsWidget = new PersonalDetailsWidget;

personalDetailsWidget.updateDetailsClick();


import {
	navAff as gamificationNavAff,
	utmParams as utmParamsRewards
} from 'globals';
import {questPopup as questPopupRewards} from 'questPopup';
import { purchaseBonus } from 'gamificationApi';

class GamificationBonus {
	constructor() {
		this.setReviewLink();
		this.setPurchasePopup();
		this.affiliateRedirect();
		this.handleOnRewardsButtonDrawerClick();
		this.handleAmplitudeEvents();
	}

	gamificationCards = document.querySelectorAll(`[data-element="gamification-card"]`);
	gamificationCardsUser = document.querySelectorAll(`[data-element="gamification-card-user"]`);

	rewardsBtnDrawer = document.querySelector(`#rewardsBtnDrawer`);
	rewardsBtnAll = document.querySelectorAll(`[data-element="rewards__btn--all"]`);

	handleOnRewardsButtonDrawerClick(){
		if(this.rewardsBtnDrawer){
			this.rewardsBtnDrawer.addEventListener(`click`, (e) => {
				e.stopPropagation();
				document.dispatchEvent(new CustomEvent('rewardsBtnDrawerShopPopup'));
			})
		}
	}

	setReviewLink = () => {
		[...this.gamificationCards, ...this.gamificationCardsUser].forEach((item, index) => {
			const casinoReviewLink = item.querySelector(`[data-element="bonus_review"]`);
			if (casinoReviewLink) {
				casinoReviewLink.addEventListener(`click`, e => {
					e.stopPropagation();

					let bonus = e.target.closest(`[data-element="gamification-card"], [data-element="gamification-card-user"]`);

					let path = bonus.dataset.path;
					let url = `/${path}/${bonus.dataset.domain}`;
					let blank = false;
					let events = {
						'event': 'TrackNavClickMainBonusesTableCasinoReviewLink',
						'eventCategory': 'TrackNav',
						'eventAction': 'ClickMainBonusesTableCasinoReviewLink',
						'eventLabel': url,
						'eventValue': index + 1
					};
					let restricted = false;
					let affLink = `review`;

					gamificationNavAff(url, blank, events, restricted, affLink);
				})
			}
		})
	}

	setPurchasePopup = () => {
		this.gamificationCards.forEach(item => {
			const purchaseBtn = item.querySelector(`[data-element="purchase-btn"]`);
			if (purchaseBtn) {
				purchaseBtn.addEventListener(`click`, e => {
					e.stopPropagation();

					let bonus = e.target.closest(`[data-element="gamification-card"]`);
					let bonusAvailable = bonus.dataset.bonusAvailable;

					this.renderPurchasePopup(bonusAvailable, bonus);
				})
			}
		})
	}

	renderPurchasePopup = (bonusAvailable, bonus) => {
		const popupWrapper = document.createElement(`div`);
		popupWrapper.className = `popupPurchase__wrapper`;

		const title = bonusAvailable ? `Want to trade your coins for this bonus?` : `Collect more coins to grab this bonus!`;

		let btns = `<button data-element="popup-purchase-drawer">Earn more coins</button><button data-element="popup-purchase-close">Back to the shop</button>`;
		if (bonusAvailable) {
			btns = `<button data-element="popup-purchase-buy">Yes, let’s do it!</button><button data-element="popup-purchase-close">No, cancel</button>`;
		}

		popupWrapper.innerHTML = `<div class="popupPurchase__block"><p class="popupPurchase__title">${title}</p><div class="popupPurchase__btns">${btns}</div></div>`

		document.body.append(popupWrapper);
		popupWrapper.classList.add(`show`);
		this.purchasePopupActions(popupWrapper, bonus);
	}

	purchasePopupActions = (popupWrapper, bonus) => {
		const bonusInfo = {
			"bonus_id": JSON.stringify(bonus.dataset.id),
			"bonus_title": JSON.stringify(bonus.querySelector(`[data-element="bonus_title"]`).innerHTML),
			"casino_domain": JSON.stringify(bonus.dataset.domain),
			"casino_name": JSON.stringify(bonus.querySelector(`[data-element="bonus_review"]`).innerHTML),
			"bonus_cost": JSON.stringify(bonus.dataset.bonusCost),
		}

		const popupPurchaseClose = popupWrapper.querySelector(`[data-element="popup-purchase-close"]`);
		popupPurchaseClose && popupPurchaseClose.addEventListener(`click`, () => {
			popupWrapper.remove();
			this.setAmplitudeRewardsParams(`click`, `p_shop_popup`, `cancelPurchase`, bonusInfo);
		});

		const popupPurchaseDrawer = popupWrapper.querySelector(`[data-element="popup-purchase-drawer"]`);
		popupPurchaseDrawer && popupPurchaseDrawer.addEventListener(`click`, () => {
			popupWrapper.remove();
			setTimeout(()=>questPopupRewards.showPopup(), 100);
		});

		const popupPurchaseBuy = popupWrapper.querySelector(`[data-element="popup-purchase-buy"]`);
		popupPurchaseBuy && popupPurchaseBuy.addEventListener(`click`, async () => {
			this.setAmplitudeRewardsParams(`click`, `p_shop_popup`, `confirmPurchase`, bonusInfo);
			try{
				const response = await purchaseBonus(bonus.dataset.id ?? 1);
				if(response.success) document.location.href = `/profile/shop`;
				else console.log(response);
			} catch(err){
				console.log(err);
			}
		});
	}

	affiliateRedirect = () => {
		this.gamificationCardsUser.forEach((item, index) => this.affiliateItemRedirect(item, index));
	}

	affiliateItemRedirect(item, index) {
		item.addEventListener(`click`, e => {
			e.stopPropagation();
			this.affiliateRedirectItem(item, index);
		})
	}

	affiliateRedirectItem(item, index) {
		let url = item.dataset.domain + `?bonus=${item.dataset.bonus}`;
		let blank = true;
		let events = {
			'event': 'TrackOffersClickMainBonusesTableAffiliateLink',
			'eventCategory': 'TrackOffers',
			'eventAction': 'ClickMainBonusesTableAffiliateLink',
			'eventLabel': item.dataset.domain,
			'eventValue': index + 1
		};
		let restricted = false;
		let affLink = item.dataset.affiliate;

		const bonusInfo = {
			"bonus_id": JSON.stringify(item.dataset.id),
			"bonus_title": JSON.stringify(item.querySelector(`[data-element="bonus_title"]`).innerHTML),
			"casino_domain": JSON.stringify(item.dataset.domain),
			"casino_name": JSON.stringify(item.querySelector(`[data-element="bonus_review"]`).innerHTML),
			"bonus_cost": JSON.stringify(item.dataset.bonusCost),
		}
		this.setAmplitudeRewardsParams(`clickAffLink`, `p_profile_rewards`, `getBonus`, bonusInfo);

		gamificationNavAff(url, blank, events, restricted, affLink)
	}

	handleAmplitudeEvents(){
		this.rewardsBtnAll.forEach(item => {
			item.addEventListener(`click`, () => {
				this.setAmplitudeRewardsParams(`click`, `p_profile_rewards`, `allBonuses`);
			})
		})

		const purchaseBtns = document.querySelectorAll(`[data-element="purchase-btn"]`);
		purchaseBtns.forEach(item => {
			item.addEventListener(`click`, (e) => {
				let bonus = e.target.closest(`[data-element="gamification-card"]`);

				const bonusInfo = {
					"bonus_id": JSON.stringify(bonus.dataset.id),
					"bonus_title": JSON.stringify(bonus.querySelector(`[data-element="bonus_title"]`).innerHTML),
					"casino_domain": JSON.stringify(bonus.dataset.domain),
					"casino_name": JSON.stringify(bonus.querySelector(`[data-element="bonus_review"]`).innerHTML),
					"bonus_cost": JSON.stringify(bonus.dataset.bonusCost),
				}

				this.setAmplitudeRewardsParams(`click`, `p_profile_rewards`, `buyNow`, bonusInfo);
			})
		})
	}

	setAmplitudeRewardsParams = (event, event_cat, event_name, bonusObj={}) => {
		const eventID = ["p_bonus_spin_n", "p_bonus_amount", "p_bonus_casino", "p_bonus_category", "p_bonus_country", "p_bonus_percent", "p_casino_category", "p_casino_city", "p_casino_country", "p_casino_state_usa", "p_casino_currency", "p_casino_deposit_low", "p_casino_payment", "p_casino", "p_casino_slot_soft", "p_game_category", "p_slot_category", "p_slot", "p_slot_payline", "p_blog_category", "p_blog_article", "p_website_category", "p_similar_casinos", "p_software_bonuses", "p_website_page", "p_home", "p_profile_rewards", "p_profile_shop", "p_other"];

		const ROUTE = document.body.dataset.routeBonus;
		const ROUTE__EXIST = eventID.findIndex(item => item === ROUTE);
		const EVENT__CAT = ROUTE__EXIST > -1 ? eventID[ROUTE__EXIST] : eventID[eventID.length - 1];

		const eventParams = {
			"page_url": JSON.stringify(document.location.origin + document.location.pathname),
			"page_current_path": JSON.stringify(document.location.pathname),
			"page_group": JSON.stringify(EVENT__CAT),
			"website_domain": JSON.stringify(document.location.hostname),
			"website_country": JSON.stringify(document.body.dataset.geo),
		}

		dataLayer.push(Object.assign({
			'event': `addEvents_${event}`,
			'event_id': `d-v1-e1`,
			'event_cat': event_cat,
			'event_name': event_name,
		}, eventParams, utmParamsRewards(), bonusObj));
	}
}

const gamificationBonus = new GamificationBonus();


import {changePassword} from "authApi";

class ChangePasswordWidget {

	/**
	 *
	 * @type {HTMLElement}
	 */
	authNewPasswordInput = document.getElementById('authNewPasswordInput');

	/**
	 *
	 * @type {HTMLElement}
	 */
	authConfirmNewPasswordInput = document.getElementById('authConfirmNewPasswordInput');

	/**
	 *
	 * @type {HTMLElement}
	 */
	changePasswordWidgetSaveButton = document.getElementById('changePasswordWidgetSaveButton');

	/**
	 *
	 * @type {HTMLElement}
	 */
	changePasswordError = document.getElementById('changePasswordError');

	/**
	 *
	 * @type {HTMLElement}
	 */
	changePasswordConfirm = document.getElementById('changePasswordConfirm');

	/**
	 *
	 * @type {HTMLElement}
	 */
	authNewPasswordShow = document.getElementById('authNewPasswordShow');

	/**
	 *
	 * @type {HTMLElement}
	 */
	authNewPasswordConfirmShow = document.getElementById('authNewPasswordConfirmShow');

	changePasswordClick() {
		this.changePasswordWidgetSaveButton.addEventListener('click', async () => {
			this.errorsClear();

			if (this.authNewPasswordInput.value === this.authConfirmNewPasswordInput.value) {
				let updatePasswordData = await changePassword(
					this.authNewPasswordInput.value,
				);

				if (updatePasswordData['changePassword']) {
					this.successMessageGenerateHTML();
					this.errorsClear();

					setTimeout(() => {
						window.location.pathname = '/profile';
					}, 1200);
				}

				this.errorRequest(updatePasswordData);
			}
		});
	}

	successMessageGenerateHTML() {
		let html = `
            <div class="success" id="passwordChangeSuccessMessage">
                <div class="success_box">
                    <svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                        <path d="M12 22C6.477 22 2 17.523 2 12C2 6.477 6.477 2 12 2C17.523 2 22 6.477 22 12C22 17.523 17.523 22 12 22ZM12 20C14.1217 20 16.1566 19.1571 17.6569 17.6569C19.1571 16.1566 20 14.1217 20 12C20 9.87827 19.1571 7.84344 17.6569 6.34315C16.1566 4.84286 14.1217 4 12 4C9.87827 4 7.84344 4.84286 6.34315 6.34315C4.84285 7.84344 4 9.87827 4 12C4 14.1217 4.84285 16.1566 6.34314 17.6569C7.84344 19.1571 9.87827 20 12 20ZM11.003 16L6.76 11.757L8.174 10.343L11.003 13.172L16.659 7.515L18.074 8.929L11.003 16Z" fill="white"/>
                    </svg>
                    <p class="text">Password was updated</p>
                </div>
            </div>
        `;

		document.body.insertAdjacentHTML('beforeend', html);

		const passwordChangeSuccessMessage = document.getElementById('passwordChangeSuccessMessage');

		passwordChangeSuccessMessage.style.animation = 'show 0.5s forwards ease-in-out';

		this.hideSuccessMessage(
			passwordChangeSuccessMessage
		);
	}

	errorsClear() {
		this.changePasswordError.innerHTML = '';
	}

	showPassword() {
		this.authNewPasswordShow.addEventListener('click', () => {
			if (this.authNewPasswordInput.type === 'password') {
				this.authNewPasswordInput.type = 'text';
			} else {
				this.authNewPasswordInput.type = 'password';
			}
		});

		this.authNewPasswordConfirmShow.addEventListener('click', () => {
			if (this.authConfirmNewPasswordInput.type === 'password') {
				this.authConfirmNewPasswordInput.type = 'text';
			} else {
				this.authConfirmNewPasswordInput.type = 'password';
			}
		});
	}

	/**
	 *
	 * @returns {this is HTMLElement[]}
	 */
	confirmPasswordInput() {
		const authNewPasswordInput = this.authNewPasswordInput;
		const authConfirmNewPasswordInput = this.authConfirmNewPasswordInput;

		const inputElements = [authNewPasswordInput, authConfirmNewPasswordInput];

		inputElements.forEach(el => {
			el.addEventListener('input', () => {
				if (authNewPasswordInput.value !== authConfirmNewPasswordInput.value) {
					this.changePasswordConfirm.innerHTML = 'Password is not the same';
				} else {
					this.changePasswordConfirm.innerHTML = '';
				}
			});
		});
	}

	/**
	 *
	 * @param element
	 */
	hideSuccessMessage(element) {
		setTimeout(() => {
			element.remove();
		}, 2000);
	}

	/**
	 *
	 * @param error
	 */
	errorRequest(error) {
		if (Object.keys(error['errors']).length) {
			this.changePasswordError.innerHTML = error['errors']['password'] ?? '';
		}
	}
}

const changePasswordWidget = new ChangePasswordWidget;

changePasswordWidget.changePasswordClick();
changePasswordWidget.showPassword();
changePasswordWidget.confirmPasswordInput();


const bonusCalculator = document.querySelector(`#bonusCalculator`),
	gameContributionInput = document.querySelector(`#gameContribution`),
	gameContributionSpan = document.querySelector(`span#gameContributionValue`),
	averageStakeInput = document.querySelector(`#averageStake`),
	averageStakeSpan = document.querySelector(`span#averageStakeValue`),
	decimalFormat = value => value.toFixed(2);
document.addEventListener('DOMContentLoaded', () => {
	gameContributionInput.addEventListener('input', e => {
		gameContributionSpan.innerHTML = e.target.value
		calculateBonuses();
	});
	averageStakeInput.addEventListener('input', e => {
		averageStakeSpan.innerHTML = e.target.value
		calculateBonuses();
	});

	document.addEventListener('click', e => {
		const {target} = e;
		if (target.matches('.qty-group__btn--plus')) {
			e.preventDefault();
			const input = target.closest('.qty-group').querySelector('input[type="number"]');
			increaseInputValue(input);
			calculateBonuses();
		}
		if (target.matches('.qty-group__btn--minus')) {
			e.preventDefault();
			const input = target.closest('.qty-group').querySelector('input[type="number"]');
			decreaseInputValue(input);
			calculateBonuses();
		}
	})

	bonusCalculator.addEventListener(`change`, () => {
		calculateBonuses();
	});
})

function increaseInputValue(input) {
	input.value++;
}

function decreaseInputValue(input) {
	if (input.value > 0) {
		input.value--;
	}
}

function calculateBonuses() {
	let depositAmount = +document.querySelector(`#depositAmountValue`).value,
		bonusPercentage = +document.querySelector(`#bonusPercentageValue`).value,
		wagerRequirement = +document.querySelector(`#wageringRequirementValue`).value,
		bonusAmount = document.querySelector('input[name=bonusAmount]:checked').id,
		gameContribution = gameContributionInput.value,
		averageStake = averageStakeInput.value,

		bonusAmountValue = document.querySelector(`#bonusAmountValue`),
		totalBalanceValue = document.querySelector(`#totalBalanceValue`),
		wagerAmountValue = document.querySelector(`#wagerAmountValue`),
		completionValue = document.querySelector(`#completionValue`);

	bonusAmountValue.innerHTML = decimalFormat(parseFloat(depositAmount) * bonusPercentage / 100);
	totalBalanceValue.innerHTML = decimalFormat(parseFloat(depositAmount) + parseFloat(bonusAmountValue.innerHTML));

	let wagerContribution = gameContribution > 0 ? 100 / gameContribution : 0;

	wagerAmountValue.innerHTML = decimalFormat(bonusAmount === 'bonusAmountDeposit'
		?
		(bonusAmountValue.innerHTML * wagerRequirement + depositAmount * wagerRequirement) * wagerContribution
		:
		bonusAmountValue.innerHTML * wagerRequirement * wagerContribution);

	let t = parseFloat(wagerAmountValue.innerHTML) / parseFloat(averageStake);
	completionValue.innerHTML = t > 0 ? decimalFormat(parseFloat(t) / 720) : decimalFormat(0);
}


class CasinoSupportAndContactsWidget {

	/**
	 *
	 * @type {HTMLCollectionOf<Element>}
	 */
	supportContactsCountryShow = document.getElementsByClassName('support_contacts-country-show');

	/**
	 *
	 * @type {HTMLCollectionOf<Element>}
	 */
	countryGroupDisabled = document.getElementsByClassName('country_group-disabled');

	onClickShowCountries() {
		Array.from(this.supportContactsCountryShow).forEach((s, index) => {
			s.addEventListener('click', () => {
				const shortGroup = s.closest('.country_group').querySelector('.country_group-short');
				shortGroup.remove();
				this.countryGroupDisabled[index].classList.add('country_group-disabled--active');
				s.remove();
			});
		});
	}
}

const casinoSupportAndContactsWidget = new CasinoSupportAndContactsWidget;

window.onload = () => {
	casinoSupportAndContactsWidget.onClickShowCountries();
}






import {appendStaticContentCarousel as appendStaticContentSlotCarousel} from "/build/midori/assets/js/staticContentCarousel.js";

document.addEventListener('DOMContentLoaded', () => {
	appendStaticContentSlotCarousel();
});


class CasinoCTAWidget {

	/**
	 *
	 * @type {HTMLElement}
	 */
	casinoCtaDescription = document.getElementById('casinoCtaDescription');

	casinoCtaDescriptionParagraph = document.querySelectorAll('#casinoCtaDescription .casino_bonus-info-info-box--more-content');

	/**
	 *
	 * @type {HTMLElement}
	 */
	casinoCtaDescriptionMore = document.getElementById('casinoCtaDescriptionMore');

	onLoadDescriptionShowMore() {
		if (this.casinoCtaDescriptionParagraph.length) {
			this.casinoCtaDescriptionParagraph.forEach(block => {
				let children = [...block.children];
				if (children.length > 1) {
					const showMoreBtn = document.createElement(`span`);
					showMoreBtn.innerHTML = `Read more`;
					showMoreBtn.className = `casino_bonus-info-intro-btn`;
					showMoreBtn.addEventListener(`click`, () => {
						children.forEach(item => {
							switch (item.localName) {
								case `table`:
									item.style.display = `table`;
									break;
								case `span`:
								case `a`:
									item.style.display = `inline`;
									break;
								default:
									item.style.display = `block`;
							}
						});
						showMoreBtn.remove();
					})
					children[0].append(showMoreBtn);
				}
			})
		}
	}
}

const casinoCTAWidget = new CasinoCTAWidget;

window.onload = () => {
	casinoCTAWidget.onLoadDescriptionShowMore();
}


import {navAff as popularSlotsNavAff} from "globals";

class PopularSlotsWidget {

	popularSlotsItems = Array.from(document.querySelectorAll('.popularSlotsWidget__item'));

	initPopularSLotsWidget() {
		if (this.popularSlotsItems.length > 0) {
			this.popularSlotsItems.forEach(el => {
				this.clickPopularSlotsItem(el);
			})
		}
	}

	clickPopularSlotsItem(item) {
		item.addEventListener('click', e => {
			const {target} = e;
			if (target.closest('.popularSlotsWidget__item--descr') ||
				target.closest('.popularSlotsWidget__item--btn-mob') ||
				target.closest('.popularSlotsWidget__item--btn-desk')
			) {
				this.redirectToAffLink(item.dataset.url, item.dataset.restricted, item.dataset.afflink);
			}
		})
	}

	redirectToAffLink(url, restricted, afflink) {
		popularSlotsNavAff(url, true, '', restricted, afflink)
	}
}

document.addEventListener('DOMContentLoaded', () => {
	const popularSlotWidget = new PopularSlotsWidget();
	popularSlotWidget.initPopularSLotsWidget();
})


import {fadeToggle as generalFadeToggle, navAff as generalNavForm} from "globals";
import {AffLinksPopup} from "afflinksPopup";
import {geoCloudflareLocation, getOffersByClientLocation} from "api";

class CasinoGeneralInfoWidget extends AffLinksPopup {
	generalLicenseMore = document.querySelector('.general__license--more');
	generalSiteBtn = document.querySelector('.general__site--btn');
	generalLocalCountry = document.querySelector(`body`).dataset.localeCountry.toLowerCase();
	showMoreBtns = document.querySelectorAll('.general__more');

    constructor() {
        super();
        this.localCountry = this.generalLocalCountry;
    }

    initEvents() {
        if (this.generalLicenseMore) {
            this.generalLicenseMore.querySelector('span.text').innerHTML = this.generalLocalCountry === 'pl' ? 'Pokaż' : 'Show';
            this.generalLicenceMoreBtnClick(this.generalLicenseMore)
        }

		if (this.generalSiteBtn) {
			this.generalSiteBtnClick(this.generalSiteBtn)
		}

		this.showMoreClickFn();
	}

	generalLicenceMoreBtnClick(element) {
		element.addEventListener('click', () => {
			generalFadeToggle(element.previousElementSibling);
			if (element.classList.contains('active')) {
				element.querySelector('span.text').innerHTML = this.generalLocalCountry === 'pl' ? 'Pokaż' : 'Show';
				element.querySelector('span.number').style.display = 'inline';
				element.classList.remove('active');
			} else {
				element.querySelector('span.text').innerHTML = this.generalLocalCountry === 'pl' ? 'Ukryj' : 'Hide';
				element.querySelector('span.number').style.display = 'none';
				element.classList.add('active');
			}
		})
	}

	async initOffers() {
		let clientLocation = document.body.dataset.geo;

		if (!clientLocation) clientLocation = await geoCloudflareLocation();

		this.loc = clientLocation.toLowerCase();

		this.data = await getOffersByClientLocation(this.loc);
	}

	affLinksRestricted(restricted, url, casinoName, affLink) {
		let restrictedArray = restricted ? restricted.split(',').map(country => country.toLowerCase()) : [];
		let countryRestricted = false;

		if (this.loc && restrictedArray.length) {
			countryRestricted = restrictedArray.find(country => country === this.loc);
		}

		if (countryRestricted || !affLink) {
			if (this.selector.children.length === 0) {
				this.generatePopup();
				this.affLinksAppendDescription(url, casinoName);
				this.affLinksRedirectClick(url, restricted, affLink);
			}
			document.body.classList.add('bonusesPopup__show')
			this.selector.classList.add('show');
			let allItemsBonusBlock = Array.from(this.selector.querySelectorAll('.bonusesPopup__item__bonus '));
			this.bonusesPopupEqualBonusHeight(allItemsBonusBlock);
		} else {
			generalNavForm(url, true, false, false, true);
		}
	}

	showMoreClickFn(){
		if(this.showMoreBtns.length){
			this.showMoreBtns.forEach(el => {
				el.addEventListener('click', () => {
					const parentWrapper = el.closest('.general__items');
					const visibleBlock = parentWrapper.querySelector('.general__items-visible');
					const hiddenBlock = parentWrapper.querySelector('.general__items-hidden');
					if (hiddenBlock.classList.contains('general__items-hidden--active')) {
						hiddenBlock.classList.remove('general__items-hidden--active');
					} else {
						hiddenBlock.classList.add('general__items-hidden--active');
						visibleBlock.remove();
						el.remove();
					}
				})
			})
		}
	}

	generalSiteBtnClick(el) {
		this.initOffers()
		el.addEventListener('click', () => {
			return this.affLinksRestricted(
				el.dataset.restricted,
				el.dataset.url,
				el.dataset.name,
				el.dataset.affiliate
			)
		})
	}
}

const casinoGeneralInfoWidget = new CasinoGeneralInfoWidget();

casinoGeneralInfoWidget.initEvents();


class CasinoCardWidget {

	/**
	 *
	 * @type {HTMLElement}
	 */
	casinoCardScrollToLink = document.getElementById('casinoCardScrollToLink');

	/**
	 *
	 * @type {HTMLElement}
	 */
	casinoScoreWidget = document.querySelector('[data-widget-handler="CasinoScoreWidget"]');

	scrollTo() {
		this.casinoCardScrollToLink ? this.casinoCardScrollToLink.addEventListener('click', () => {
			this.casinoScoreWidget ? this.casinoScoreWidget.scrollIntoView({
				behavior: 'smooth',
				block: 'center'
			}) : null;
		}) : null;
	}
}

/**
 *
 * @type {CasinoCardWidget}
 */
const casinoCardWidget = new CasinoCardWidget;

casinoCardWidget.scrollTo();


class CasinoCardWidgetBonusSocial {
    header = document.querySelector('.header');
    scrollButton = document.querySelectorAll('.casinoCardWidgetBonusSocial__btn-scroll-btn');

    scrollButtonClick() {
        if (this.scrollButton) {
            this.scrollButton.forEach(item => {
                item.addEventListener('click', (e) => {
                    e.preventDefault();
                    let scrollButtonTarget = item.dataset.target;
                    let blockToScrollDataId = document.querySelector(`[data-id="${scrollButtonTarget}"]`);
                    let blockToScrollId = document.querySelector(`#${scrollButtonTarget}`);

                    scrollButtonTarget = blockToScrollId ? blockToScrollId : blockToScrollDataId ? blockToScrollDataId : this.firstBlock();

                    if (!scrollButtonTarget) {
                        return;
                    }

                    const scrollButtonTargetOffset = scrollButtonTarget.getBoundingClientRect().top

                    setTimeout(() => {
                        window.scroll({
                            top: scrollButtonTargetOffset + (window.scrollY - this.header.offsetHeight),
                            behavior: 'smooth'
                        });
                    }, 100);
                })
            })
        }
    }

    firstBlock() {
        for (let i = 1; i <= 100; i++) {
            let elementId = "block_" + i;
            let element = document.querySelector(`[data-id="${elementId}"]`);

            if (element) {
                return element;
            }
        }
        return null
    }
}
const casinoCardWidgetBonusSocial = new CasinoCardWidgetBonusSocial();

casinoCardWidgetBonusSocial.scrollButtonClick();


class CasinoCardWidgetReviewSocial {
    /**
     *
     * @type {Element}
     */
    header = document.querySelector('.header');

    /**
     *
     * @type {Element}
     */
    scrollLink = document.querySelector('.casinoCardWidgetReviewSocial__card-score-values .link');

    /**
     *
     * @type {NodeListOf<Element>}
     */
    scrollButton = document.querySelectorAll('.casinoCardWidgetReviewSocial__btn-scroll-btn');

    /**
     *
     * @type {Element}
     */
    casinoScoreWidget = document.querySelector('[data-widget-handler="CasinoScoreWidget"]');

    init(){
        this.scrollButtonClick();
        this.scrollLinkClick();
    }
    scrollButtonClick() {
        if (this.scrollButton) {
            this.scrollButton.forEach(item => {
                item.addEventListener('click', (e) => {
                    e.preventDefault();
                    let scrollButtonTarget = item.dataset.target;
                    let blockToScrollDataId = document.querySelector(`[data-id="${scrollButtonTarget}"]`);
                    let blockToScrollId = document.querySelector(`#${scrollButtonTarget}`);

                    scrollButtonTarget = blockToScrollId ? blockToScrollId : blockToScrollDataId ? blockToScrollDataId : this.firstBlock();

                    if (!scrollButtonTarget) {
                        return;
                    }

                    const scrollButtonTargetOffset = scrollButtonTarget.getBoundingClientRect().top

                    setTimeout(() => {
                        window.scroll({
                            top: scrollButtonTargetOffset + (window.scrollY - this.header.offsetHeight),
                            behavior: 'smooth'
                        });
                    }, 100);
                })
            })
        }
    }

    scrollLinkClick() {
        this.scrollLink ? this.scrollLink.addEventListener('click', () => {
            this.casinoScoreWidget ? this.casinoScoreWidget.scrollIntoView({
                behavior: 'smooth',
                block: 'center'
            }) : null;
        }) : null;
    }

    firstBlock() {
        for (let i = 1; i <= 100; i++) {
            let elementId = "block_" + i;
            let element = document.querySelector(`[data-id="${elementId}"]`);

            if (element) {
                return element;
            }
        }
        return null
    }
}

/**
 *
 * @type {CasinoCardWidgetReviewSocial}
 */
const casinoCardWidgetReviewSocial = new CasinoCardWidgetReviewSocial();

casinoCardWidgetReviewSocial.init();



class CasinoInfoWidget {
	casinoInfoWidgetTables = Array.from(document.querySelectorAll('.casinoInfoWidget__table'));

	casinoInfoWidgetInit() {
		if (!this.casinoInfoWidgetTables) {
			return;
		}
		this.casinoInfoWidgetEvents()
	}

	casinoInfoWidgetEvents() {
		this.casinoInfoWidgetTables.forEach(item => {
			item.addEventListener('click', e => {
				const {target} = e;
				if (target.closest('.casinoInfoWidget__more-btn')) {
					const currentBtn = target.closest('.casinoInfoWidget__more-btn');
					const parentItem = currentBtn.parentElement;
					const parentTd = parentItem.parentElement;

					if (parentItem.classList.contains('casinoInfoWidget__show-more')) {
						parentItem.classList.remove('casinoInfoWidget__show-more')
						parentTd.classList.add('casinoInfoWidget__show-items')
					}
				}
			})
		})
	}
}

const casinoInfoWidget = new CasinoInfoWidget();

document.addEventListener('DOMContentLoaded', () => {
	casinoInfoWidget.casinoInfoWidgetInit();
})


const accordionList = document.querySelectorAll('.accordion__wrapper .accordion');

if (accordionList.length > 0) {
	const accordionWrapper = document.querySelector('.accordion__wrapper');
	accordionWrapper.addEventListener('click', e => {
		const {target} = e;
		if (target.closest('.accordion__card-title')) {
			e.preventDefault();
			const accordion = target.closest('.accordion');
			if (accordion.classList.contains('accordion__card-active')) {
				closeAccordion(accordion);
			} else {
				openAccordion(accordion);
			}
		}
	})
}

function openAccordion(accordion) {
	const content = accordion.querySelector(".accordion__card-content");
	content.style.height = content.scrollHeight + 'px';
	accordion.classList.add("accordion__card-active");
}

function closeAccordion(accordion) {
	const content = accordion.querySelector(".accordion__card-content");
	content.style.height = 0;
	accordion.classList.remove("accordion__card-active");
}


import {fadeOut, fadeIn} from "globals";

let summaryBtn = document.querySelectorAll('.table-of-content__dropdown__button');

summaryBtn.forEach(el => {
	el.addEventListener('click', e => {
		e.stopPropagation();

		let summaryBlock = el.nextElementSibling;

		if (el.classList.contains(`active`)) {
			el.classList.remove(`active`);
			fadeOut(summaryBlock);
		} else {
			el.classList.add(`active`);
			fadeIn(summaryBlock);
		}
	})
});

window.addEventListener(`click`, () => {
	let summaryBlockActive = document.querySelector('.table-of-content__dropdown__button.active');

	if (summaryBlockActive) {
		summaryBlockActive.classList.remove(`active`);
		fadeOut(summaryBlockActive.nextElementSibling);
	}
})


import {
	navAff as gamificationNavAff,
	utmParams as utmParamsShop
} from 'globals';
import {questPopup as questPopupRewards} from 'questPopup';
import { purchaseBonus } from 'gamificationApi';

class GamificationBonus {
	constructor() {
		this.setReviewLink();
		this.setPurchasePopup();
		this.handleAmplitudeEvents();
	}

	gamificationCards = document.querySelectorAll(`[data-element="gamification-card"]`);

	setReviewLink = () => {
		this.gamificationCards.forEach((item, index) => {
			const casinoReviewLink = item.querySelector(`[data-element="bonus_review"]`);
			if (casinoReviewLink) {
				casinoReviewLink.addEventListener(`click`, e => {
					e.stopPropagation();

					let bonus = e.target.closest(`[data-element="gamification-card"], [data-element="gamification-card-user"]`);

					let path = bonus.dataset.path;
					let url = `/${path}/${bonus.dataset.domain}`;
					let blank = false;
					let events = {
						'event': 'TrackNavClickMainBonusesTableCasinoReviewLink',
						'eventCategory': 'TrackNav',
						'eventAction': 'ClickMainBonusesTableCasinoReviewLink',
						'eventLabel': url,
						'eventValue': index + 1
					};
					let restricted = false;
					let affLink = `review`;

					gamificationNavAff(url, blank, events, restricted, affLink);
				})
			}
		})
	}

	setPurchasePopup = () => {
		this.gamificationCards.forEach(item => {
			const purchaseBtn = item.querySelector(`[data-element="purchase-btn"]`);
			if (purchaseBtn) {
				purchaseBtn.addEventListener(`click`, e => {
					e.stopPropagation();

					let bonus = e.target.closest(`[data-element="gamification-card"]`);
					let bonusAvailable = bonus.dataset.bonusAvailable;

					this.renderPurchasePopup(bonusAvailable, bonus);
				})
			}
		})
	}

	renderPurchasePopup = (bonusAvailable, bonus) => {
		const popupWrapper = document.createElement(`div`);
		popupWrapper.className = `popupPurchase__wrapper`;

		const title = bonusAvailable ? `Want to trade your coins for this bonus?` : `Collect more coins to grab this bonus!`;

		let btns = `<button data-element="popup-purchase-drawer">Earn more coins</button><button data-element="popup-purchase-close">Back to the shop</button>`;
		if (bonusAvailable) {
			btns = `<button data-element="popup-purchase-buy">Yes, let’s do it!</button><button data-element="popup-purchase-close">No, cancel</button>`;
		}

		popupWrapper.innerHTML = `<div class="popupPurchase__block"><p class="popupPurchase__title">${title}</p><div class="popupPurchase__btns">${btns}</div></div>`

		document.body.append(popupWrapper);
		popupWrapper.classList.add(`show`);
		this.purchasePopupActions(popupWrapper, bonus);
	}

	purchasePopupActions = (popupWrapper, bonus) => {
		const bonusInfo = {
			"bonus_id": JSON.stringify(bonus.dataset.id),
			"bonus_title": JSON.stringify(bonus.querySelector(`[data-element="bonus_title"]`).innerHTML),
			"casino_domain": JSON.stringify(bonus.dataset.domain),
			"casino_name": JSON.stringify(bonus.querySelector(`[data-element="bonus_review"]`).innerHTML),
			"bonus_cost": JSON.stringify(bonus.dataset.bonusCost),
		}

		const popupPurchaseClose = popupWrapper.querySelector(`[data-element="popup-purchase-close"]`);
		popupPurchaseClose && popupPurchaseClose.addEventListener(`click`, () => {
			popupWrapper.remove();
			this.setAmplitudeRewardsParams(`click`, `p_shop_popup`, `cancelPurchase`, bonusInfo);
		});

		const popupPurchaseDrawer = popupWrapper.querySelector(`[data-element="popup-purchase-drawer"]`);
		popupPurchaseDrawer && popupPurchaseDrawer.addEventListener(`click`, () => {
			popupWrapper.remove();
			setTimeout(()=>questPopupRewards.showPopup(), 100);
		});

		const popupPurchaseBuy = popupWrapper.querySelector(`[data-element="popup-purchase-buy"]`);
		popupPurchaseBuy && popupPurchaseBuy.addEventListener(`click`, async () => {
			this.setAmplitudeRewardsParams(`click`, `p_shop_popup`, `confirmPurchase`, bonusInfo);
			try{
				const response = await purchaseBonus(bonus.dataset.id ?? 1);
				if(response.success) document.location.href = `/profile/shop`;
				else console.log(response);
			} catch(err){
				console.log(err);
			}
		});
	}

	handleAmplitudeEvents(){
		const purchaseBtns = document.querySelectorAll(`[data-element="purchase-btn"]`);
		purchaseBtns.forEach(item => {
			item.addEventListener(`click`, (e) => {
				let bonus = e.target.closest(`[data-element="gamification-card"]`);

				const bonusInfo = {
					"bonus_id": JSON.stringify(bonus.dataset.id),
					"bonus_title": JSON.stringify(bonus.querySelector(`[data-element="bonus_title"]`).innerHTML),
					"casino_domain": JSON.stringify(bonus.dataset.domain),
					"casino_name": JSON.stringify(bonus.querySelector(`[data-element="bonus_review"]`).innerHTML),
					"bonus_cost": JSON.stringify(bonus.dataset.bonusCost),
				}

				this.setAmplitudeRewardsParams(`click`, `p_profile_shop`, `buyNow`, bonusInfo);
			})
		})
	}

	setAmplitudeRewardsParams = (event, event_cat, event_name, bonusObj={}) => {
		const eventID = ["p_bonus_spin_n", "p_bonus_amount", "p_bonus_casino", "p_bonus_category", "p_bonus_country", "p_bonus_percent", "p_casino_category", "p_casino_city", "p_casino_country", "p_casino_state_usa", "p_casino_currency", "p_casino_deposit_low", "p_casino_payment", "p_casino", "p_casino_slot_soft", "p_game_category", "p_slot_category", "p_slot", "p_slot_payline", "p_blog_category", "p_blog_article", "p_website_category", "p_similar_casinos", "p_software_bonuses", "p_website_page", "p_home", "p_profile_rewards", "p_profile_shop", "p_other"];

		const ROUTE = document.body.dataset.routeBonus;
		const ROUTE__EXIST = eventID.findIndex(item => item === ROUTE);
		const EVENT__CAT = ROUTE__EXIST > -1 ? eventID[ROUTE__EXIST] : eventID[eventID.length - 1];

		const eventParams = {
			"page_url": JSON.stringify(document.location.origin + document.location.pathname),
			"page_current_path": JSON.stringify(document.location.pathname),
			"page_group": JSON.stringify(EVENT__CAT),
			"website_domain": JSON.stringify(document.location.hostname),
			"website_country": JSON.stringify(document.body.dataset.geo),
		}

		dataLayer.push(Object.assign({
			'event': `addEvents_${event}`,
			'event_id': `d-v1-e1`,
			'event_cat': event_cat,
			'event_name': event_name,
		}, eventParams, utmParamsShop(), bonusObj));
	}

}

const gamificationBonus = new GamificationBonus();


import {getTermsAndConditions as restrictedTNC} from "api";
import {navAff as restrictedNavAff, getLocaleCountry as __brw_localeCountry, utmParams as utmParamsRestricted, eventID as eventIDRestricted} from "globals";
import {__translate as __brw_translate} from "translate";
import {centrifugeManager as bonusRestrictedCentrifugeManager} from 'CentrifugeManager';

class RestrictedBlock {

	noAmplitudeParam = new URLSearchParams(document.location.search).get("no-amplitude");

	/**
	 *
	 * @type {Element}
	 */
	countriesPopup = document.querySelector('.restrictedBlock__popup-countries__wrapper');

	/**
	 *
	 * @type {T[]}
	 */
	restrictedCards = Array.from(document.querySelectorAll('.restrictedBlock__card'));

	/**
	 *
	 * @type {T[]}
	 */
	restrictedCardsContent = Array.from(document.querySelectorAll('.restrictedBlock__card__content'));

	/**
	 *
	 * @type {[string]}
	 */
	tncCountries = [`GB`];

	promoCode = document.querySelectorAll('[data-element="bonus_promo"]');

	restrictedBlockInit() {
		document.addEventListener('click', (e) => {
			const {target} = e;
			if (target.closest('.restrictedBlock__top__change')) {
				this.countriesPopup.classList.add('show')
				document.body.classList.add('restrictedBlock__popup-countries__show')
			} else if (target.closest('.restrictedBlock__popup-countries__close') || target.closest('.restrictedBlock__popup-countries__item')) {
				this.countriesPopup.classList.remove('show')
				document.body.classList.remove('restrictedBlock__popup-countries__show')
			}
		})
		this.restrictedCards.forEach(item => {
			item.addEventListener('click', (e) => {
				const {target} = e;

				if (target.closest('.restrictedBlock__card__after--select')) {
					this.onClickShowTnc(item, item.dataset.bonus, item.dataset.termsUrl)
				} else if (!target.closest('.restrictedBlock__card__top__info--reviews')
					&& !e.target.classList.contains('show-more-link')) {
					e.preventDefault();
					let events = {
						'event': 'TrackOffersClickMainBonusesTableAffiliateLink',
						'eventCategory': 'TrackOffers',
						'eventAction': 'ClickMainBonusesTableAffiliateLink',
						'eventLabel': item.dataset.domain,
						'eventValue': +item.dataset.widget_list_index + 1
					};
					bonusRestrictedCentrifugeManager.publishCustomEvent('bonusClicked', {
						bonusId: item.dataset.bonus,
						isSponsored: item.dataset.sponsored
					});
					this.restrictedBtnClick(item.dataset.url, item.dataset.blank, events, item.dataset.restricted, item.dataset.affiliate)
				}
			})
		})
		this.tncShow();
		this.onClickPromoCodeLoop();
		this.showLogo();
		this.showWhyLink();
	}

	restrictedBtnClick(url, blank, events, restricted, affLink) {
		restrictedNavAff(url, blank, events, restricted, affLink);
	}

	async onClickShowTnc(item, bonus_id, termsUrl) {
		const innerTerms = document.createElement('div');
		innerTerms.classList.add('restrictedBlock__card__after--content');

		let tacContent = item.querySelector('.restrictedBlock__card__after--content');
		let tacElement = item.querySelector('.restrictedBlock__card__after--select__txt');

		if (item.classList.contains('tac-show') && tacContent) {
			tacContent.parentNode.removeChild(tacContent);
			setTimeout(() => item.classList.remove('tac-show'), 100)
			return;
		}

		const tnc = await this.getTerms(bonus_id)
		item.classList.add('tac-show')
		innerTerms.innerHTML = `<span class="restrictedBlock__card__after--text">${tnc}</span>`;
		item.append(innerTerms);
		this.onClickTncText(item);

		this.tncShowMore(tnc, innerTerms);
	}

	tncShowMore(contentText, element) {
		const limit = 160;

		if (contentText.length > limit) {
			const truncatedText = contentText.slice(0, limit);
			const hiddenText = contentText.slice(limit);
			element.innerHTML =
				`<span class="restrictedBlock__card__after--text">` + truncatedText + `<span class="hidden-text">${hiddenText}</span><span class="show-more-link">... ${__brw_translate('Show more', __brw_localeCountry()) ?? 'Show more'}</span></span>`;

			const showMoreLink = element.querySelector('.show-more-link');
			const hiddenTextSpan = element.querySelector('.hidden-text');

			showMoreLink.addEventListener('click', () => {
				if (hiddenTextSpan.style.display !== 'none' || hiddenTextSpan.style.display !== '') {
					hiddenTextSpan.style.display = 'inline';
					showMoreLink.textContent = '';
				} else {
					hiddenTextSpan.style.display = 'none';
					showMoreLink.textContent = `... ${__brw_translate('Show more', __brw_localeCountry()) ?? 'Show more'}`;
				}
			});

			return element;
		}

		return element.innerHTML;
	}

	tncShow() {
		let loc = document.body.dataset.geo;

		if (this.tncCountries.includes(loc)) {
			this.restrictedCards.forEach(async item => {
				const innerTerms = document.createElement('div');
				innerTerms.classList.add('restrictedBlock__card__after--content');

				let tacContent = item.querySelector('.restrictedBlock__card__after--content');
				let tacElement = item.querySelector('.restrictedBlock__card__after--select__txt');
				let bonusId = item.dataset.bonus;

				if (item.classList.contains('tac-show') && tacContent) {
					tacContent.parentNode.removeChild(tacContent);
					setTimeout(() => item.classList.remove('tac-show'), 100)
					return;
				}

				const tnc = await this.getTerms(bonusId)
				item.classList.add('tac-show')
				innerTerms.innerHTML = `<span class="restrictedBlock__card__after--text">${tnc}</span>`;
				item.append(innerTerms);
				this.onClickTncText(item);
				this.tncShowMore(tnc, innerTerms);
			})
		}
	}

	onClickTncText(item) {
		let termsUrl = item.dataset.termsUrl;
		let termsLink = item.querySelector('.restrictedBlock__card__after--text');

		termsUrl && termsLink.addEventListener(`click`, e => {
			e.stopPropagation();
			if (!e.target.classList.contains('show-more-link')) {
				!this.noAmplitudeParam && this.amplitudeTC(e);
				window.open(termsUrl, `_blank`);
			}
		})
	}

	amplitudeTC = el => {
		const table = el.target.closest(`.restrictedBlock__cards, .restrictedBlock__cards__less`);

		const element = {
			items: table.dataset.items ? JSON.parse(table.dataset.items) : ``,
			route: table.dataset.route,
			widgetId: table.dataset.widgetId,
			widgetTitle: table.dataset.widgetTitle,
			widgetHandler: table.dataset.widgetHandler,
			widgetNotice: table.dataset.widgetNotice,
			widgetBonusCountry: table.dataset.widgetBonusCountry,
			widgetCasinoCountry: table.dataset.widgetCasinoCountry,
			widgetArguments: table.dataset.widgetArguments ? JSON.parse(table.dataset.widgetArguments) : ``,
			eventCat: "w_website",
			eventAffClickName: "tc_redirect",
			clickAffLinkVersion: 48
		};

		const tr = el.target.closest(`.restrictedBlock__card`),
			index = tr.dataset.widget_list_index - 1,
			data = element.items ? element.items[index] : '',
			btnName = tr.dataset.casino_bonus_button_name,
			tncLink = tr.dataset.termsUrl;

		let casinoUserCountryAllowed = false;

		let pageAffLinkClickIndex = storage.getPageAffLinkClickIndex();
		pageAffLinkClickIndex++;
		storage.setPageAffLinkClickIndex(pageAffLinkClickIndex);

		const amplitudeVersion = 1;

		dataLayer.push(Object.assign(
			{
				'event': 'addEvents_click',
				'event_id': `d-v${amplitudeVersion}-e${element.clickAffLinkVersion}`,
				'event_cat': element.eventCat,
				'event_name': element.eventAffClickName,
				"casino_bonus_button_name": JSON.stringify(btnName),
				"widget_list_index": JSON.stringify(tr.dataset.widget_list_index),
				"casino_user_country_allowed": JSON.stringify(casinoUserCountryAllowed),
				"page_afflink_click_index": JSON.stringify(pageAffLinkClickIndex),
				"redirect_link": JSON.stringify(tncLink)
			},
			this.newPageData(element),
			this.newBonusData(data),
			utmParamsRestricted())
		);
	}

	newPageData = element => {
		let ROUTE = document.body.dataset.routeBonus,
			ROUTE__ID = document.body.dataset.routeId,
			ROUTE__EXIST = eventIDRestricted.findIndex(item => item === ROUTE),
			EVENT__ID = ROUTE__EXIST > -1 ? ROUTE__EXIST + 1 : eventIDRestricted.length,
			EVENT__CAT = ROUTE__EXIST > -1 ? eventIDRestricted[ROUTE__EXIST] : eventIDRestricted[eventIDRestricted.length - 1],
			PAGE__CURRENT__PATH = document.location.pathname,
			PAGE__URL = document.location.origin + document.location.pathname,
			PAGE__URL__FULL = document.location.href,
			LOCALE__LANG = document.body.dataset.localeLang,
			WEBSITE__ENVIRONMENT = document.body.dataset.websiteEnv,
			LOCALE__COUNTRY = document.body.dataset.geo,
			COUNTRY__BACKEND = document.body.dataset.geo;

		return {
			"page_current_path": JSON.stringify(PAGE__CURRENT__PATH),
			"page_url": JSON.stringify(PAGE__URL),
			"page_url_full": JSON.stringify(PAGE__URL__FULL),
			"page_group": JSON.stringify(EVENT__CAT),
			"widget_title": JSON.stringify(element.widgetTitle),
			"widget_id": JSON.stringify(element.widgetId),
			"page_route_id": JSON.stringify(ROUTE__ID),
			"widget_handler": JSON.stringify(element.widgetHandler),
			"casino_list_user_country": JSON.stringify(COUNTRY__BACKEND),
			"casino_user_country": JSON.stringify(COUNTRY__BACKEND),
			"casino_list_for_geo": JSON.stringify(element.widgetBonusCountry ? element.widgetBonusCountry : element.widgetCasinoCountry ? element.widgetCasinoCountry : false)
		}
	};

	newBonusData = data => {
		let casinoScoreGeoText = ``;
		switch (data.score) {
			case data.score === 5:
				casinoScoreGeoText = `A`;
				break;
			case data.score > 4.5 && data.score <= 4.9:
				casinoScoreGeoText = `B`;
				break;
			case data.score > 4 && data.score <= 4.5:
				casinoScoreGeoText = `C`;
				break;
			case data.score <= 4:
				casinoScoreGeoText = `D`;
				break;
		}

		return {
			"casino_bonus_title_short": JSON.stringify(data.titleShort ? data.titleShort : null),
			"casino_bonus_title_short_strlen": JSON.stringify(data.titleShort ? data.titleShort.length : 0),
			"casino_id": JSON.stringify(data.casino ? data.casino.casinoId : null),
			"casino_name": JSON.stringify(data.casino ? data.casino.name : null),
			"casino_domain": JSON.stringify(data.casino ? data.casino.domain : null),
			"casino_bonus_amount_max": JSON.stringify(data.amountMax && !isNaN(parseInt(data.amountMax)) ? parseInt(data.amountMax) : 0),
			"casino_bonus_percent": JSON.stringify(data.percent ? data.percent : 0),
			"casino_bonus_exclusive": JSON.stringify(data.exclusive ? true : false),
			"casino_bonus_cashable": JSON.stringify(data.cashable ? true : false),
			"casino_bonus_expired": JSON.stringify(data.expired ? true : false),
			"casino_bonus_id": JSON.stringify(data.id),
			"casino_domain_bonus_id": JSON.stringify(data.casino ? `${data.casino.domain}_${data.id}` : null),
			"casino_score_geo": JSON.stringify(data.score ? data.score.toFixed(1) : null),
			"casino_afflink_exist": JSON.stringify(data.affiliateUrl ? true : false),
			"casino_bonus_wagering_requirements": JSON.stringify(data.wageringRequirements && !isNaN(parseInt(data.wageringRequirements)) ? parseInt(data.wageringRequirements) : 0),
			"casino_bonus_deposit_min": JSON.stringify(parseInt(data.depositMin)),
			"casino_bonus_code_exist": JSON.stringify(data.code ? true : false),
			"casino_bonus_label_exist": JSON.stringify(data.label ? true : false),
			"casino_bonus_category": JSON.stringify(data.bonusCategories && Array.isArray(data.bonusCategories) ? data.bonusCategories.map(item => item.name) : null),
			"casino_bonus_label": JSON.stringify(data.label),
			"casino_bonus_type": JSON.stringify(data.bonusTypes && Array.isArray(data.bonusTypes) ? data.bonusTypes.map(item => item.name) : null),
			"casino_bonus_free_spins": JSON.stringify(data.freeSpins ? +data.freeSpins : 0),
			"casino_score_geo_text": JSON.stringify(casinoScoreGeoText),
			"sponsored": JSON.stringify(data.sponsored ? true : false)
		}
	};

	restrictedPopupEqualItemsHeight(items) {
		const highest = Math.max(...items.map(item => item.offsetHeight))
		items.forEach((el) => {
			el.style.minHeight = highest + 'px';
		})
	}

	async getTerms(bonus_id) {
		return await restrictedTNC(bonus_id)
	}

	copyText(element) {
		return navigator.clipboard.writeText(element);
	}

	onClickPromoCodeLoop() {
		this.promoCode.forEach(item => {
			item.addEventListener(`click`, e => {
				const isFakePromocode = item.dataset.isFakePromocode;

				if (!isFakePromocode) {
					e.stopPropagation();

					let tr = item.closest(`.restrictedBlock__card`);
					const isSponsored = tr.dataset.sponsored;
					const promocode = tr.querySelector(`[data-element="bonus_promo-value"]`);
					const promocodeText = promocode.innerText || promocode.dataset?.textBefore;

					this.copyText(promocodeText).then(() => {
						item.classList.contains(`copied`) && item.classList.remove(`copied`);
						item.classList.add(`coping`);

						if(!isSponsored){
							setTimeout(() => {
								item.classList.remove(`coping`);
								item.classList.add(`copied`);
							}, 1500)
						}

						setTimeout(() => {
							tr.click();
						}, 3000)
					});
				}
			})
		})
	}

	showLogo(){
		this.restrictedCards.forEach(item => {
			const logoBlock = item.querySelector(`[data-element="logo__block"]`);
			const hiddenImg = item.querySelector(`[data-element="hidden__img"]`);
			const hiddenImgSrc = hiddenImg && hiddenImg.dataset.src;

			const img = document.createElement(`img`);
			img.src = hiddenImgSrc;

			logoBlock && logoBlock.append(img);
		})
	}

	showWhyLink(){
		const restrictedBlockWhy = document.querySelector(`[data-element="restrictedBlock__why"]`);
		if(restrictedBlockWhy){
			const link = restrictedBlockWhy.querySelector(`[data-element="restrictedBlock__why__link"]`);
			link.addEventListener(`click`, e => {
				e.stopPropagation();
				document.location.href = link.dataset.href;
			})
		}
	}
}

const restrictedBlock = new RestrictedBlock;

restrictedBlock.restrictedBlockInit();



class StaticWithBonusTableWidget {
    constructor() {
        this.cardShowMore = document.querySelectorAll('.card_showMore');
        this.cardToolbox = document.querySelectorAll('.card_toolbox');
    }

    showMore() {
        this.cardShowMore.forEach((element, index) => {
            element.addEventListener('click', (e) => {
                e.stopPropagation();
                this.cardToolbox[index] ? this.cardToolbox[index].style.display = 'block' : null;
            });

            element.addEventListener('mouseout', (e) => {
                this.cardToolbox[index] ? this.cardToolbox[index].style.display = 'none' : null;
            });

            document.addEventListener('click', (e) => {
                if (!element.contains(e.target) && this.cardToolbox[index]) {
                    this.cardToolbox[index].style.display = 'none';
                }
            });
        });
    }
}

const staticWithBonusTableWidget = new StaticWithBonusTableWidget;

staticWithBonusTableWidget.showMore();

import {getTermsAndConditions as bonusWelcomeTypeTNC} from "api";
import {__translate as __bwt_translate} from "translate";
import {
    navAff as navAffWelcomeBonus,
    getLocaleCountry as __bwt_localeCountry,
    utmParams as utmParamsBonusWelcomeType,
    eventID as eventIDWelcome
} from "globals";
import {centrifugeManager as bonusWelcomeTypeCentrifugeManager} from 'CentrifugeManager';

class BonusWelcomeTypeWidget {

    noAmplitudeParam = new URLSearchParams(document.location.search).get("no-amplitude");

    /**
     *
     * @type {T[]}
     */
    bonusWelcomeTypeWidgetCards = Array.from(document.querySelectorAll('.bonusWelcomeTypeWidget__card'));

    /**
     *
     * @type {Element}
     */
    bonusWelcomeTypeMoreBtn = document.querySelector('.bonusWelcomeTypeWidget__more-bonuses__btn');

    /**
     *
     * @type {Element}
     */
    header = document.querySelector('.header');

    /**
     *
     * @type {[string]}
     */
    tncCountries = [`GB`];

    generateTnc() {
        if (this.bonusWelcomeTypeWidgetCards.length > 0) {
            this.bonusWelcomeTypeWidgetCards.forEach(item => {
                item.addEventListener('click', (e) => {
                    const {target} = e
                    if (target.closest('.bonusWelcomeTypeWidget__card__tnc--toogle')) {
                        return this.onClickShowTnc(item, item.dataset.bonus)
                    }

                    if (!e.target.classList.contains('show-more-link')) {
                        bonusWelcomeTypeCentrifugeManager.publishCustomEvent('bonusClicked', {
                            bonusId: item.dataset.bonus,
                            isSponsored: item.dataset.sponsored
                        });
                        return navAffWelcomeBonus(item.dataset.url, item.dataset.blank, item.dataset.events, item.dataset.restricted, item.dataset.afflink)
                    }
                })
            });
            this.tncShow();
        }
    }

    moreBtnClick() {
        if (this.bonusWelcomeTypeMoreBtn) {
            this.bonusWelcomeTypeMoreBtn.addEventListener('click', (e) => {
                e.preventDefault();
                let bonusWelcomeTypeMoreBtnTarget = this.bonusWelcomeTypeMoreBtn.dataset.target
                bonusWelcomeTypeMoreBtnTarget = document.querySelector('.' + bonusWelcomeTypeMoreBtnTarget)
                if (!bonusWelcomeTypeMoreBtnTarget) {
                    return;
                }
                const bonusTableOffset = bonusWelcomeTypeMoreBtnTarget.getBoundingClientRect().top

                window.scrollTo({
                    top: bonusTableOffset + window.scrollY - this.header.offsetHeight,
                    left: 0,
                    behavior: 'smooth'
                });
            })
        }
    }

    /**
     *
     * @param item
     * @param bonus_id
     * @returns {Promise<void>}
     */
    async onClickShowTnc(item, bonus_id) {
        const innerTerms = document.createElement('div');
        innerTerms.classList.add('bonusWelcomeTypeWidget__card__tnc--content');

        const tncWrapper = item.querySelector('.bonusWelcomeTypeWidget__card__tnc');
        const tncTxt = item.querySelector('.bonusWelcomeTypeWidget__card__tnc--toogle-txt');

        let tncContent = item.querySelector('.bonusWelcomeTypeWidget__card__tnc--content');

        if (item.classList.contains('tnc-show') && tncContent) {
            tncContent.parentNode.removeChild(tncContent);
            setTimeout(() => item.classList.remove('tnc-show'), 100)
            return;
        }

        const tnc = await this.getTerms(bonus_id);

        item.classList.add('tnc-show');

        innerTerms.innerHTML = `<span class="bonusWelcomeTypeWidget__card__tnc--content-txt">${tnc}</span>`;

        this.tncShowMore(tnc, innerTerms);

        tncWrapper.insertAdjacentElement('afterend', innerTerms);

        let tnxTextBlock = innerTerms.querySelector(`.bonusWelcomeTypeWidget__card__tnc--content-txt`);

        if (tncTxt.dataset.termsUrl) {
            tnxTextBlock ? tnxTextBlock.addEventListener(`click`, e => {
                e.stopPropagation();
                if (!e.target.classList.contains('show-more-link')) {
                    !this.noAmplitudeParam && this.amplitudeTC(e);
                    window.open(tncTxt.dataset.termsUrl, `_blank`);
                }
            }) : null;
        }
    }

    /**
     *
     * @param el
     */
    amplitudeTC(el) {
        const table = el.target.closest(`.bonusWelcomeTypeWidget__cards`);

        const element = {
            items: JSON.parse(table.dataset.items),
            route: table.dataset.route,
            widgetId: table.dataset.widgetId,
            widgetTitle: table.dataset.widgetTitle,
            widgetHandler: table.dataset.widgetHandler,
            widgetNotice: table.dataset.widgetNotice,
            widgetBonusCountry: table.dataset.widgetBonusCountry,
            widgetCasinoCountry: table.dataset.widgetCasinoCountry,
            widgetArguments: table.dataset.widgetArguments ? JSON.parse(table.dataset.widgetArguments) : ``,
            eventCat: "w_website",
            eventAffClickName: "tc_redirect",
            clickAffLinkVersion: 48
        };

        const tr = el.target.closest(`.bonusWelcomeTypeWidget__card`),
            index = tr.dataset.widget_list_index - 1,
            data = element.items[index],
            btnName = tr.dataset.casino_bonus_button_name,
            tncLink = tr.dataset.termsUrl;

        let casinoUserCountryAllowed = true;

        let pageAffLinkClickIndex = storage.getPageAffLinkClickIndex();
        pageAffLinkClickIndex++;
        storage.setPageAffLinkClickIndex(pageAffLinkClickIndex);

        const amplitudeVersion = 1;

        dataLayer.push(Object.assign(
            {
                'event': 'addEvents_click',
                'event_id': `d-v${amplitudeVersion}-e${element.clickAffLinkVersion}`,
                'event_cat': element.eventCat,
                'event_name': element.eventAffClickName,
                "casino_bonus_button_name": JSON.stringify(btnName),
                "widget_list_index": JSON.stringify(tr.dataset.widget_list_index),
                "casino_user_country_allowed": JSON.stringify(casinoUserCountryAllowed),
                "page_afflink_click_index": JSON.stringify(pageAffLinkClickIndex),
                "redirect_link": JSON.stringify(tncLink)
            },
            this.newPageData(element),
            this.newBonusData(data),
            utmParamsBonusWelcomeType())
        );
    }

    /**
     *
     * @param element
     * @returns {{page_url: string, page_current_path: string, casino_list_for_geo: string, page_url_full: string, page_group: string, widget_id: string, page_route_id: string, widget_title: string, casino_user_country: string, widget_handler: string, casino_bonus_short: string, casino_list_user_country: string}}
     */
    newPageData(element) {
        let ROUTE = document.body.dataset.routeBonus,
            ROUTE__ID = document.body.dataset.routeId,
            ROUTE__EXIST = eventIDWelcome.findIndex(item => item === ROUTE),
            EVENT__CAT = ROUTE__EXIST > -1 ? eventIDWelcome[ROUTE__EXIST] : eventIDWelcome[eventIDWelcome.length - 1],
            PAGE__CURRENT__PATH = document.location.pathname,
            PAGE__URL = document.location.origin + document.location.pathname,
            PAGE__URL__FULL = document.location.href,
            COUNTRY__BACKEND = document.body.dataset.geo;

        return {
            "page_current_path": JSON.stringify(PAGE__CURRENT__PATH),
            "page_url": JSON.stringify(PAGE__URL),
            "page_url_full": JSON.stringify(PAGE__URL__FULL),
            "page_group": JSON.stringify(EVENT__CAT),
            "widget_title": JSON.stringify(element.widgetTitle),
            "widget_id": JSON.stringify(element.widgetId),
            "page_route_id": JSON.stringify(ROUTE__ID),
            "widget_handler": JSON.stringify(element.widgetHandler),
            "casino_list_user_country": JSON.stringify(COUNTRY__BACKEND),
            "casino_user_country": JSON.stringify(COUNTRY__BACKEND),
            "casino_list_for_geo": JSON.stringify(element.widgetBonusCountry ? element.widgetBonusCountry : element.widgetCasinoCountry ? element.widgetCasinoCountry : false)
        }
    };

    /**
     *
     * @param score
     * @returns {string}
     */
    calculateCasinoScoreGeoText(score) {
        if (score === 5) return 'A';
        if (score > 4.5 && score <= 4.9) return 'B';
        if (score > 4 && score <= 4.5) return 'C';

        return 'D';
    };

    /**
     *
     * @param data
     * @returns {{casino_id: string, casino_bonus_title_short_strlen: string, casino_bonus_title_short: string, casino_bonus_id: string, casino_bonus_type: string, casino_bonus_deposit_min: string, casino_bonus_code_exist: string, casino_bonus_percent: string, casino_domain: string, casino_score_geo: string, casino_bonus_exclusive: string, casino_bonus_special_button_title: string, casino_bonus_label_exist: string, casino_bonus_category: string, casino_domain_bonus_id: string, casino_bonus_free_spins: string, casino_bonus_cashable: string, casino_bonus_wagering_requirements: string, casino_bonus_title_long: string, casino_bonus_title_long_strlen: string, casino_score_geo_text: string, casino_name: string, casino_afflink_exist: string, casino_bonus_label: string, casino_bonus_amount_max: string, casino_bonus_expired: string}}
     */
    newBonusData(data) {
        const casinoScoreGeoText = this.calculateCasinoScoreGeoText(data.score.toFixed(1));

        return {
            "casino_bonus_title_short": JSON.stringify(data.titleShort ? data.titleShort : ''),
            "casino_bonus_title_short_strlen": JSON.stringify(data.titleShort ? data.titleShort.length : 0),
            "casino_id": JSON.stringify(data.casino.casinoId),
            "casino_name": JSON.stringify(data.casino.name),
            "casino_domain": JSON.stringify(data.casino.domain),
            "casino_bonus_amount_max": JSON.stringify(data.amountMax && !isNaN(parseInt(data.amountMax)) ? parseInt(data.amountMax) : 0),
            "casino_bonus_percent": JSON.stringify(data.percent ? data.percent : 0),
            "casino_bonus_exclusive": JSON.stringify(!!data.exclusive),
            "casino_bonus_cashable": JSON.stringify(!!data.cashable),
            "casino_bonus_expired": JSON.stringify(!!data.expired),
            "casino_bonus_id": JSON.stringify(data.id),
            "casino_domain_bonus_id": JSON.stringify(`${data.casino.domain}_${data.id}`),
            "casino_score_geo": JSON.stringify(data.score.toFixed(1)),
            "casino_afflink_exist": JSON.stringify(!!data.affiliateUrl),
            "casino_bonus_wagering_requirements": JSON.stringify(data.wageringRequirements && !isNaN(parseInt(data.wageringRequirements)) ? parseInt(data.wageringRequirements) : 0),
            "casino_bonus_deposit_min": JSON.stringify(parseInt(data.depositMin)),
            "casino_bonus_code_exist": JSON.stringify(!!data.code),
            "casino_bonus_label_exist": JSON.stringify(!!data.label),
            "casino_bonus_category": JSON.stringify(data.bonusCategories && Array.isArray(data.bonusCategories) ? data.bonusCategories.map(item => item.name) : ''),
            "casino_bonus_label": JSON.stringify(data.label),
            "casino_bonus_type": JSON.stringify(data.bonusTypes && Array.isArray(data.bonusTypes) ? data.bonusTypes.map(item => item.name) : ''),
            "casino_bonus_free_spins": JSON.stringify(data.freeSpins ? +data.freeSpins : 0),
            "casino_score_geo_text": JSON.stringify(casinoScoreGeoText),
            "sponsored": JSON.stringify(data.sponsored ? true : false)
        }
    };

    tncShow() {
        let loc = document.body.dataset.geo;

        if (this.tncCountries.includes(loc)) {
            this.bonusWelcomeTypeWidgetCards.forEach(async item => {
                const innerTerms = document.createElement('div');
                innerTerms.classList.add('bonusWelcomeTypeWidget__card__tnc--content');

                const tncWrapper = item.querySelector('.bonusWelcomeTypeWidget__card__tnc');
                const tncTxt = item.querySelector('.bonusWelcomeTypeWidget__card__tnc--toogle-txt');
                let bonusId = item.dataset.bonus;

                let tncContent = item.querySelector('.bonusWelcomeTypeWidget__card__tnc--content');
                if (item.classList.contains('tnc-show') && tncContent) {
                    tncContent.parentNode.removeChild(tncContent);
                    setTimeout(() => item.classList.remove('tnc-show'), 100)
                    return;
                }

                const tnc = await this.getTerms(bonusId)
                item.classList.add('tnc-show')
                innerTerms.innerHTML = `<span class="bonusWelcomeTypeWidget__card__tnc--content-txt">${tnc}</span>`;
                tncWrapper.insertAdjacentElement('afterend', innerTerms);

                let tnxTextBlock = innerTerms.querySelector(`.bonusWelcomeTypeWidget__card__tnc--content-txt`);

                if (tncTxt.dataset.termsUrl) {
                    tnxTextBlock.addEventListener(`click`, e => {
                        e.stopPropagation();
                        window.open(tncTxt.dataset.termsUrl, `_blank`);
                    })
                }

                this.tncShowMore(innerTerms, tnxTextBlock)
            })
        }
    }

    /**
     *
     * @param contentText
     * @param element
     * @returns {string}
     */
    tncShowMore(contentText, element) {
        const limit = 160;

        if (contentText.length > limit) {
            const truncatedText = contentText.slice(0, limit);
            const hiddenText = contentText.slice(limit);
            element.innerHTML = truncatedText + `<span class="hidden-text">${hiddenText}</span><span class="show-more-link">... ${__bwt_translate('Show more', __bwt_localeCountry()) ?? 'Show more'}</span>`;

            const showMoreLink = element.querySelector('.show-more-link');
            const hiddenTextSpan = element.querySelector('.hidden-text');

            showMoreLink.addEventListener('click', () => {
                if (hiddenTextSpan.style.display !== 'none' || hiddenTextSpan.style.display !== '') {
                    hiddenTextSpan.style.display = 'inline';
                    showMoreLink.textContent = '';
                } else {
                    hiddenTextSpan.style.display = 'none';
                    showMoreLink.textContent = `... ${__bwt_translate('Show more', __bwt_localeCountry()) ?? 'Show more'}`;
                }
            });

            return element;
        }

        return element.innerHTML;
    }

    /**
     *
     * @param casino_id
     * @returns {Promise<*>}
     */
    async getTerms(casino_id) {
        return await bonusWelcomeTypeTNC(casino_id)
    }
}

const bonusWelcomeTypeWidget = new BonusWelcomeTypeWidget;

bonusWelcomeTypeWidget.generateTnc();
bonusWelcomeTypeWidget.moreBtnClick();



import {
	navAff as gamificationNavUserAff,
	utmParams as utmParamsShopUser
} from 'globals';

class GamificationUserBonus {
	constructor() {
		this.setReviewLink();
		this.affiliateRedirect();
	}

	gamificationCardsUser = document.querySelectorAll(`[data-element="gamification-card-user"]`);

	setReviewLink = () => {
		this.gamificationCardsUser.forEach((item, index) => {
			const casinoReviewLink = item.querySelector(`[data-element="bonus_review"]`);
			if (casinoReviewLink) {
				casinoReviewLink.addEventListener(`click`, e => {
					e.stopPropagation();

					let bonus = e.target.closest(`[data-element="gamification-card"], [data-element="gamification-card-user"]`);

					let path = bonus.dataset.path;
					let url = `/${path}/${bonus.dataset.domain}`;
					let blank = false;
					let events = {
						'event': 'TrackNavClickMainBonusesTableCasinoReviewLink',
						'eventCategory': 'TrackNav',
						'eventAction': 'ClickMainBonusesTableCasinoReviewLink',
						'eventLabel': url,
						'eventValue': index + 1
					};
					let restricted = false;
					let affLink = `review`;

					gamificationNavUserAff(url, blank, events, restricted, affLink);
				})
			}
		})
	}

	affiliateRedirect = () => {
		this.gamificationCardsUser.forEach((item, index) => this.affiliateItemRedirect(item, index));
	}

	affiliateItemRedirect(item, index) {
		item.addEventListener(`click`, e => {
			e.stopPropagation();
			this.affiliateRedirectItem(item, index);
		})
	}

	affiliateRedirectItem(item, index) {
		let url = item.dataset.domain + `?bonus=${item.dataset.bonus}`;
		let blank = true;
		let events = {
			'event': 'TrackOffersClickMainBonusesTableAffiliateLink',
			'eventCategory': 'TrackOffers',
			'eventAction': 'ClickMainBonusesTableAffiliateLink',
			'eventLabel': item.dataset.domain,
			'eventValue': index + 1
		};
		let restricted = false;
		let affLink = item.dataset.affiliate;

		const bonusInfo = {
			"bonus_id": JSON.stringify(item.dataset.id),
			"bonus_title": JSON.stringify(item.querySelector(`[data-element="bonus_title"]`).innerHTML),
			"casino_domain": JSON.stringify(item.dataset.domain),
			"casino_name": JSON.stringify(item.querySelector(`[data-element="bonus_review"]`).innerHTML),
			"bonus_cost": JSON.stringify(item.dataset.bonusCost),
		}
		this.setAmplitudeRewardsParams(`clickAffLink`, `p_profile_rewards`, `getBonus`, bonusInfo);

		gamificationNavUserAff(url, blank, events, restricted, affLink)
	}

	setAmplitudeRewardsParams = (event, event_cat, event_name, bonusObj={}) => {
		const eventID = ["p_bonus_spin_n", "p_bonus_amount", "p_bonus_casino", "p_bonus_category", "p_bonus_country", "p_bonus_percent", "p_casino_category", "p_casino_city", "p_casino_country", "p_casino_state_usa", "p_casino_currency", "p_casino_deposit_low", "p_casino_payment", "p_casino", "p_casino_slot_soft", "p_game_category", "p_slot_category", "p_slot", "p_slot_payline", "p_blog_category", "p_blog_article", "p_website_category", "p_similar_casinos", "p_software_bonuses", "p_website_page", "p_home", "p_profile_rewards", "p_profile_shop", "p_other"];

		const ROUTE = document.body.dataset.routeBonus;
		const ROUTE__EXIST = eventID.findIndex(item => item === ROUTE);
		const EVENT__CAT = ROUTE__EXIST > -1 ? eventID[ROUTE__EXIST] : eventID[eventID.length - 1];

		const eventParams = {
			"page_url": JSON.stringify(document.location.origin + document.location.pathname),
			"page_current_path": JSON.stringify(document.location.pathname),
			"page_group": JSON.stringify(EVENT__CAT),
			"website_domain": JSON.stringify(document.location.hostname),
			"website_country": JSON.stringify(document.body.dataset.geo),
		}

		dataLayer.push(Object.assign({
			'event': `addEvents_${event}`,
			'event_id': `d-v1-e1`,
			'event_cat': event_cat,
			'event_name': event_name,
		}, eventParams, utmParamsShopUser(), bonusObj));
	}

}

const gamificationUserBonus = new GamificationUserBonus();


