(function ($) {
    "use strict";
    const setCookie = (name, value, days) => {
        let expires = "";
        if (days) {
            const date = new Date();
            date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
            expires = "; expires=" + date.toUTCString();
        }
        document.cookie = name + "=" + (value || "")  + expires + "; path=/";
    };

    const getCookie = (name) => {
        const nameEQ = name + "=";
        const ca = document.cookie.split(';');
        for(let i=0; i < ca.length; i++) {
            let c = ca[i];
            while (c.charAt(0) === ' ') c = c.substring(1, c.length);
            if (c.indexOf(nameEQ) === 0) return c.substring(nameEQ.length, c.length);
        }
        return null;
    };

    const initSifencyProtectedContent = ($scope) => {
        const wrapper = $scope.find('.sifency-protected-wrapper')[0];
        if (!wrapper) return;

        const config = JSON.parse(wrapper.getAttribute('data-config'));
        const cookieName = 'sifency_unlocked_' + config.id;
        
        const lockScreen = wrapper.querySelector('.sifency-protected-lock-screen');
        const form = wrapper.querySelector('.sf-password-form');
        const input = wrapper.querySelector('.sf-password-input');
        const errorMsg = wrapper.querySelector('.sf-error-msg');
        const contentDest = wrapper.querySelector('.sifency-unlocked-content');
        const secretTemplate = wrapper.querySelector('.sf-secret-data');

        const unlockContent = () => {
            const decodedHTML = decodeURIComponent(atob(secretTemplate.innerHTML));
            
            contentDest.innerHTML = decodedHTML;
            lockScreen.style.display = 'none';
            contentDest.style.display = 'block';

            if (window.elementorFrontend) {
                $(contentDest).find('[data-element_type]').each(function() {
                    elementorFrontend.elementsHandler.runReadyTrigger($(this));
                });
            }
        };

        if (config.cookie && getCookie(cookieName) === 'true') {
            unlockContent();
            return;
        }

        if (form) {
            form.addEventListener('submit', (e) => {
                e.preventDefault();
                const userPass = input.value.trim();

                if (config.passwords.includes(userPass)) {
                    errorMsg.style.display = 'none';
                    if (config.cookie) setCookie(cookieName, 'true', config.days);
                    unlockContent();
                } else {
                    errorMsg.style.display = 'block';
                    form.classList.add('sf-shake');
                    setTimeout(() => form.classList.remove('sf-shake'), 400);
                }
            });
        }
    };

    $(window).on('elementor/frontend/init', () => {
        elementorFrontend.hooks.addAction('frontend/element_ready/sifency-protected-content.default', initSifencyProtectedContent);
    });
})(jQuery);