if (!window.dashboardAuth) {
    function dashboardAuthSetup() {
        function onMessage(event) {
            if (!event.isTrusted) return;
            if (event.origin !== 'https://dashboard.visme.co') return;

            if (event.data === 'ewc-close') {
                closeLoginForm();
            }
            else if (event.data === 'ewc-auth') {
                authUser(false)
                    .then(function(result) {
                        closeLoginForm(result);
                    })
                    .catch(function() {
                        closeLoginForm(false);
                    });
            }
        }
        window.addEventListener('message', onMessage);

        function obtainToken() {
            return fetch('https://dashboard.visme.co/api/auth/refresh', {
                method: 'GET',
                cache: 'no-cache',
                credentials: 'include',
                redirect: 'error',
            }).then(function(response) {
                return response.text();
            }).catch(function() {
                return "";
            });
        }

        function loadUser(token) {
            return fetch('https://dashboard.visme.co/api/auth/user-info?source_type='+encodeURI(loginSourceType), {
                method: 'GET',
                cache: 'no-cache',
                credentials: 'omit',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                    'Authorization': 'Bearer '+token,
                },
                redirect: 'error',
            })
            .then(function(response) { return response.json();})
            .then(function(result) {
                if (result.status == "success" && result.data && result.data.userId > 0) {
                    result.data.isLoggedIn = true;
                    return result.data;
                } else {
                    return {isLoggedIn: false};
                }
            });
        }

        function authUser(showLogin, sourceType = '') {
            if (sourceType && sourceType != '') loginSourceType = sourceType;
            return new Promise(function(resolve, reject) {
                obtainToken().then(function(token) {
                    if (!token) {
                        if (showLogin)
                            triggerLoginForm(sourceType).then(resolve).catch(reject);
                        else
                            resolve({isLoggedIn: false});
                    } else {
                        loadUser(token).then(resolve).catch(reject);
                    }
                })
            });

        }

        var loginIframe = null;
        var loginFormPromise = null;
        var loginFormResolve = null;
        var loginFormReject = null;
        var loginSourceType = '';

        function triggerLoginForm(sourceType) {
            if (loginFormPromise != null) return loginFormPromise;

            loginFormPromise = new Promise(function (resolve, reject) {
                loginFormResolve = resolve;
                loginFormReject = reject;
            });

            if (loginIframe === null) {
                loginIframe = document.createElement('iframe');
                loginIframe.style.position = 'fixed';
                loginIframe.style.left = '0';
                loginIframe.style.top = '0';
                loginIframe.style.width = '100vw';
                loginIframe.style.height = '100vh';
                loginIframe.style.border = '0';
                loginIframe.style.zIndex = '15000';
                document.body.appendChild(loginIframe);
            }
            if (sourceType == 'editor-guest' || sourceType == 'editor-guest-register') {
                loginIframe.setAttribute('src', 'https://dashboard.visme.co/v2/register?ewcauth=1&guest=1');
            }
            else if (sourceType == 'editor-guest-login') {
                loginIframe.setAttribute('src', 'https://dashboard.visme.co/v2/login?ewcauth=1&guest=1');
            }
            else if (sourceType == 'visme-course') {
                loginIframe.setAttribute('src', 'https://dashboard.visme.co/v2/register?ewcauth=1');
            }
            else {
                loginIframe.setAttribute('src', 'https://dashboard.visme.co/v2/login?ewcauth=1');
            }

            return loginFormPromise;
        }

        function closeLoginForm(user) {
            if (loginFormPromise === null) return;

            document.body.removeChild(loginIframe);
            loginIframe = null;

            if (user)
                loginFormResolve(user);
            else
                loginFormResolve({isLoggedIn: false});
            loginFormPromise = null;
        }

        window.dashboardAuth = {
            authUser,
        }
    }
    dashboardAuthSetup();
}
