function loadFacebookAPI() {
    var js = document.createElement('script');
    js.src = 'https://connect.facebook.net/hu_HU/sdk.js#xfbml=1&version=v4.0&appId=676805345831827&autoLogAppEvents=1';
    document.body.appendChild(js);
}

let set;

function setCookieSettings() {
    let cookieSetting = document.getElementById('qc-cmp2-persistent-link');

    if (!cookieSetting) {
        return;
    }

    cookieSetting.click();
}

function getCookie(name) {
    const d = {};
    document.cookie.split('; ').forEach(item => {
        d[item.split('=')[0]] = item.split('=')[1];
    });

    return d[name];
}

function setCookie(name, value, exdays) {
    var d = new Date();
    d.setTime(d.getTime() + (exdays * 24 * 60 * 60 * 1000));
    var expires = 'expires=' + d.toUTCString();
    document.cookie = `${name}=${value}; ${expires}; path=/`;
}

function deleteCookie(name, value) {
    var expires = 'expires=Thu, 01 Jan 1970 00:00:01 GMT';
    document.cookie = `${name}=${value}; ${expires}; path=/`;
}

function documentReady(fn) {
    if (document.readyState === 'complete' || document.readyState === 'interactive') {
        fn();
    } else {
        document.addEventListener('DOMContentLoaded', fn);
    }
}

const handleMenuClose = e => {
    const prevScroll = window.scrollY;
    window.location.replace('#');
    window.scrollTo(0, prevScroll);
    history.replaceState('', document.title, window.location.pathname + window.location.search);
};

document.addEventListener('click', event => {
    const isClickInsideHamburgerMenu = document.querySelector('#hamburgerMenu')?.contains(event.target);
    const isClickInsideElementHamburgerOpenButton = document.querySelector('#hamburgerOpenButton')?.contains(event.target);

    if (!isClickInsideHamburgerMenu && !isClickInsideElementHamburgerOpenButton && window.location.href.endsWith('#mainHeader')) {
        handleMenuClose();
    }
});

const toggleHamburgerButtons = document.getElementsByClassName('toggleHamburger');

for (const button of Object.values(toggleHamburgerButtons)) {
    if (button) {
        button.addEventListener('click', e => {
            if (window.location.href.endsWith('#mainHeader')) {
                e.preventDefault();
                handleMenuClose();
            } else {
                e.preventDefault();
                const prevScroll = window.scrollY;
                window.location.replace('#mainHeader');
                window.scrollTo(0, prevScroll);
            }
        });
    }
}

$(window).ready(() => {
    if (!getCookie('isLeavingPopUpReady') && document.querySelector('.leavingPopupLayer')) {
        const showPopup = () => {
            setCookie('isLeavingPopUpReady', false, 3);
            document.querySelector('body').style.overflow = 'hidden';
            document.querySelector('.leavingPopupLayer').style.display = 'block';
            document.querySelector('.leavingPopupLayer div').classList.add('fade-in');
        };

        document.documentElement.addEventListener('mouseleave', showPopup);

        const checkModalClose = e => {
            if ($(e.target).hasClass('leavingPopupLayer')) {
                closeModal();
            }
        };

        const closeModal = () => {
            document.querySelector('body').style.overflow = 'hidden auto';
            document.querySelector('.leavingPopupLayer').classList.add('fade-out');
            document.querySelector('html').removeEventListener('click', checkModalClose);
            document.querySelector('.leavingPopupLayer .close').removeEventListener('click', closeModal);
            document.documentElement.removeEventListener('mouseleave', showPopup);
        };

        document.querySelector('.leavingPopupLayer .close').addEventListener('click', closeModal);
        document.querySelector('html').addEventListener('click', checkModalClose);
    }
});

function closePopup() {
    $('#articleOfferFlag').remove();
}

documentReady(() => {
    window.addEventListener('message', e => {
        if (e.data.eventType === 'loginRedirect') {
            let sourceParam = '';

            if (e.data.case) {
                sourceParam += e.data.case;
            }

            if (window.articleUuid) {
                sourceParam += '_' + window.articleUuid;
            }

            const form = document.createElement('form');
            form.method = 'POST';
            form.action = `https://www.kiskegyed.hu/login`;

            if (sourceParam) {
                const input = document.createElement('input');
                input.type = 'hidden';
                input.name = 'source';
                input.value = sourceParam;
                form.appendChild(input);
            }

            document.body.appendChild(form);
            form.submit();
        }
    });

    window.onscroll = function () {
        if ($('#articleOfferFlag').length && $('#articleOfferFlagPosition').length) {
            if (document.querySelector('#articleOfferFlagPosition').getBoundingClientRect().top - 200 < window.innerHeight) {
                $('#articleOfferFlag').addClass('slideInRight');
            } else {
                $('#articleOfferFlag').removeClass('slideInRight');
            }
        }

        if ($('#featuredVideo').length) {
            if ($('#featuredVideo').attr('data-ga4event-fired') === 'false' && document.querySelector('#featuredVideo').getBoundingClientRect().bottom - 200 < window.innerHeight) {
                $('#featuredVideo').attr('data-ga4event-fired', 'true');
                window.dataLayer = window.dataLayer || [];
                window.dataLayer.push({ 'event': 'scrolled-to-featured-video' });
            }
        }
    };

    let lastScroll = window.scrollY;

    function handleStickyHeader() {
        const header = document.querySelector('#mainHeader');

        if (header) {
            const currentScroll = window.scrollY;

            if (currentScroll <= header.offsetHeight * 0.6) {
                header.classList.remove('hideMenu');
            } else if (lastScroll - currentScroll > -200 && lastScroll - currentScroll < 0) {
                header.classList.add('hideMenu');
            } else {
                header.classList.remove('hideMenu');
            }

            lastScroll = currentScroll;
        }
    }

    function toggleMobileSearchBar(searchTogglerSelector, inputContainerSelector) {
        document.querySelector('#searchContainer')?.classList.toggle('show');

        if (document.querySelector('#searchContainer')?.classList.contains('show')) {
            document.querySelector(`${searchTogglerSelector} span`).innerText = 'Kereső bezárása';
            document.querySelector(`${searchTogglerSelector} .searchIcon`).style.display = 'none';
            document.querySelector(`${searchTogglerSelector} .closeIcon`).style.display = 'block';
            document.querySelector(`${inputContainerSelector} input`).focus();
        } else {
            document.querySelector(`${searchTogglerSelector} span`).innerText = 'Keresés';
            document.querySelector(`${searchTogglerSelector} .searchIcon`).style.display = 'block';
            document.querySelector(`${searchTogglerSelector} .closeIcon`).style.display = 'none';
        }
    }

    document.querySelector('#openSearchBar')?.addEventListener('click', () => {
        document.querySelector('#searchContainer')?.classList.add('show');
        document.querySelector(`.inputContainer input`).focus();
    });

    document.querySelector('.closeSearchField')?.addEventListener('click', () => {
        toggleMobileSearchBar('#mobileSearchToggler', '.inputContainer');
    });

    document.querySelector('#mobileSearchToggler')?.addEventListener('click', () => {
        handleMenuClose();
        toggleMobileSearchBar('#mobileSearchToggler', '.inputContainer');
    });

    document.querySelector('.mobileSearchCloseIcon').addEventListener('click', () => {
        toggleMobileSearchBar('#mobileSearchToggler');
    });

    document.addEventListener('scroll', handleStickyHeader);

    document.querySelector('#hamburgerCloseButton')?.addEventListener('click', () => {
        handleMenuClose();
    });

    document.querySelectorAll('.shareAPIButton')?.forEach(button => {
        button.addEventListener('click', () => {
            navigator.share({
                title: button?.dataset?.shareTitle,
                text: button?.dataset?.shareText,
                url: button?.dataset?.shareUrl
            });
        });
    });

    document.querySelectorAll('[link-url]')?.forEach(element => {
        element.addEventListener('click', () => window.open(element?.attributes[0]?.value, '_blank').focus());
    });

    $('.applyAdult').click(() => {
        $('#adultAlert').fadeOut('fast');
        sessionStorage.adultAlert = 1;
    });

    document.querySelectorAll('#detailPage .image .dropdown-menu a')?.forEach(link => {
        link.addEventListener('click', () => {
            window.open(link.href, '_blank');
        });
    });
    const newsletterElement = document.querySelector('form.newsletterSubscription');

    if (newsletterElement) {
        document.querySelectorAll('[data-hidden-input]')?.forEach((input, hiddenIdx) => {
            if (!input) {
                return;
            }

            const hiddenInput = document.querySelector(
                `[name="${input.dataset.hiddenInput}"]`
            );
            input.addEventListener('change', e => {
                if (e.target.checked) {
                    hiddenInput.value = 'subscribed';
                } else {
                    hiddenInput.value = 'not subscribed';
                }
            });
        });

        newsletterElement.addEventListener('submit', e => {
            e.preventDefault();
            const formData = new FormData(e.target);
            const filteredFormData = {};

            for (const [name, value] of formData.entries()) {
                if (value !== 'not subscribed') {
                    filteredFormData[name] = value;
                }
            }

            const purifiedFormData = Object.entries(filteredFormData).reduce((prev, [key, value]) => {
                if (!key.includes('_frequency')) {
                    prev[key] = value;

                    return prev;
                }

                if (!filteredFormData.hasOwnProperty(key.replace('frequency', 'subscription'))) {
                    return prev;
                }

                prev[key] = value;

                return prev;
            }, {});

            const formProps = Object.fromEntries(formData);

            if (formProps?.interest !== 'on') {
                document.querySelectorAll('input[name=\'interest\']').forEach((e, index) => {
                    setTimeout(() => e.classList.add('shakeAnimation'), index * 6);
                    setTimeout(() => e.classList.remove('shakeAnimation'), 2000);
                });

                return;
            }

            const sailthruForm = new FormData();

            for (const [name, value] of Object.entries(purifiedFormData)) {
                if (name.startsWith('vars') || name === 'name' || name === 'email') {
                    sailthruForm.append(name, value);
                }
            }

            const edm = formData.get('promotions_subscription');

            if (edm.valueOf() === 'subscribed') {
                sailthruForm.append('vars[promotions_subscription]', edm.valueOf());
            }

            sailthruForm.append('vars[nl_subscription]', 'subscribed');

            const ga4EventList = [];

            for (const [key, value] of sailthruForm.entries()) {
                if (value === 'subscribed') {
                    const newsletterName = key.replace(/^vars\[nl_(.*?)_subscription\]$/, '$1');

                    if (!newsletterName.includes('vars')) {
                        ga4EventList.push(newsletterName + '_' + sailthruForm.get('vars[nl_' + newsletterName + '_frequency]'));
                    }
                }
            }

            sendForm(sailthruForm, ga4EventList);
        });
        const subscribeCheckbox = document.querySelector('form.newsletterSubscription #subscribe');

        if (subscribeCheckbox) {
            subscribeCheckbox.addEventListener('change', e => {
                if (e.target.checked) {
                    document
                        .querySelector('.newsletterSubscription .interests')
                        .classList.add('open');
                } else {
                    document
                        .querySelector('.newsletterSubscription .interests')
                        .classList.remove('open');
                }
            });

            subscribeCheckbox.removeAttribute('disabled');
        }
    }

    async function sendForm(formData, ga4EventList) {
        const submitButton = document.querySelector(
            'form.newsletterSubscription button[type=\'submit\']'
        );

        const prevButtonBackgroundColor = submitButton.style.background;
        const prevButtonBorderColor = submitButton.style.borderColor;

        submitButton.innerHTML = 'Küldés';
        submitButton.style.background = '#1e78aa';
        submitButton.style.borderColor = '#1e78aa';

        let formSuccess = false;

        try {
            await fetch('https://www.kiskegyed.hu/sailthru', {
                method: 'POST',
                body: formData
            }).then(() => {
                submitButton.style.background = '#8fcf8f';
                submitButton.style.borderColor = '#8fcf8f';
                submitButton.innerHTML = 'Feliratkozva';
                const customEvent = new Event('successfulSailthruNewsletterSubscription');
                setTimeout(() => {
                    document
                        .querySelector('.newsletterSubscription .interests')
                        .classList.remove('open');
                    document.querySelector('.newsletterSubscription').reset();
                    submitButton.style.background = prevButtonBackgroundColor;
                    submitButton.style.borderColor = prevButtonBorderColor;
                    submitButton.innerHTML = 'Feliratkozás';
                    document.dispatchEvent(customEvent);
                }, 2000);

                formSuccess = true;
            });
        } catch (e) {
            formSuccess = false;
            console.error(e);
            submitButton.style.background = '#ee5b5b';
            submitButton.style.borderColor = '#ee5b5b';
            submitButton.innerHTML = 'Sikertelen';
        }

        window.dataLayer = window.dataLayer || [];
        ga4EventList
            .map(newsletterName => ({
                event: 'subscribe_newsletter',
                method: 'newsletter subscription form',
                form_state: formSuccess ? 'success' : 'error',
                newsletter_list: newsletterName
            }))
            .forEach(ga4Event => window.dataLayer.push(ga4Event));
    }
});

const checkSessionCookiesExists = () => {
    const sessionId = getCookie('SessionId');
    const isLoggedIn = getCookie('Loggedin');

    const loginButton = document.querySelector('#loginButton');
    const profileButtonGroup = document.querySelector('#profileButtonGroup');

    if (sessionId && isLoggedIn === 'true') {
        loginButton.classList.remove('active');
        profileButtonGroup.classList.add('active');
    } else {
        loginButton.classList.add('active');
        profileButtonGroup.classList.remove('active');
    }
};

function sailThruCookieExchange() {
    const sessionId = getCookie('SessionId');
    const isLoggedIn = getCookie('Loggedin');
    const sailThruContent = getCookie('sailthru_content');
    const sailThruHid = getCookie('sailthru_hid');

    if (sessionId && isLoggedIn && sailThruContent && !sailThruHid) {
        fetch('https://www.kiskegyed.hu/sailthru/cookie-exchange');
    }
}

window.addEventListener('load', checkSessionCookiesExists);
window.addEventListener('load', sailThruCookieExchange);
window.addEventListener('load', addDropdownListeners);

function addDropdownListeners() {
    const dropdownActivators = document.querySelectorAll('.dropdownLabel, .dropdown');

    dropdownActivators.forEach(el => {
        el.addEventListener('mouseover', () => {
            el.parentElement.classList.add('current');

            el.addEventListener('mouseout', () => {
                el.parentElement.classList.remove('current');
            });
        });
    });
}

function prevHoroscopePagination() {
    if ($('.horoscopeText.active').prev('.horoscopeText').length !== 0) {
        $('.nextHoroscopePagination').css('display', 'block');
        $('.horoscopeText.active').removeClass('active').prev().addClass('active');
        $('.dateHoroscopePagination.active').removeClass('active').prev().addClass('active');

        if ($('.horoscopeText.active').prev('.horoscopeText').length === 0) {
            $('.prevHoroscopePagination').css('display', 'none');
        }
    }
}

function nextHoroscopePagination() {
    if ($('.horoscopeText.active').next('.horoscopeText').length !== 0) {
        $('.prevHoroscopePagination').css('display', 'block');
        $('.horoscopeText.active').removeClass('active').next().addClass('active');
        $('.dateHoroscopePagination.active').removeClass('active').next().addClass('active');

        if ($('.horoscopeText.active').next('.horoscopeText').length === 0) {
            $('.nextHoroscopePagination').css('display', 'none');
        }
    }
}
