(function() {
    var allowRetry = true
    var fetchUrl = function (url, body, cb) {
        var xhr = new XMLHttpRequest()
        xhr.open('POST', url, true)
        xhr.setRequestHeader('Content-Type', 'application/json;charset=UTF-8')
        if (window.localStorage && typeof window.localStorage.getItem === 'function') {
            var memberId = window.localStorage.getItem('syllableSession')
            if (memberId) {
                xhr.setRequestHeader('Authorization', 'Bearer ' + memberId)
            }
        }
        xhr.onload = function () {
            cb(null, this.status, this.responseText)
        }
        xhr.onerror = function () {
            cb(this.response)
        }
        xhr.send(JSON.stringify(body))
    }

    var getCurrentLanguage = function () {
        var lang
        if (window.localStorage && typeof window.localStorage.getItem === 'function') {
            lang = window.localStorage.getItem('currentLang')
        }
        return lang || 'en'
    }

    var getClientSettings = function () {
        try {
            var cookies = decodeURIComponent(document.cookie).split('; ')
            var clientSettingsCookie = (cookies.filter(function (c) {
                return c.indexOf('web-client-settings') === 0
            }) || [])[0]
            if (!clientSettingsCookie) {
                return {}
            }
            var clientSettingsStr = clientSettingsCookie
                .replace('web-client-settings=', '')
                .replace(/%20/g, ' ')
            return JSON.parse(clientSettingsStr)
        } catch (err) {
            console.warn('error getting client settings: ', err)
            return {}
        }
    }

    var fetchSettings = function (id, forceMobile, cb) {
        var payload = {
            id: id,
            metadata: {
                title: window.document.title,
                url: window.location.href,
                referrer: window.document.referrer,
                mobile: false,
                lang: getCurrentLanguage(),
            },
            force_mobile: forceMobile,
        }

        var clientSettings = getClientSettings()
        if (clientSettings.id === id) {
            payload.client_settings = {
                shim_version: clientSettings.shim_version,
                mode: clientSettings.mode,
            }
        }

        fetchUrl('https://winston-production.syllable.ai/get_settings_web', payload, cb)
    }

    var injectShim = function (shimUrl) {
        var script = document.createElement('script')
        script.async = true
        script.src = shimUrl
        document.head.appendChild(script)
    }

    var onReceiveSettings = function (error, status, settings) {
        if (error) {
            return
        }
        if (status === 401 && allowRetry) {
            if (window.localStorage && typeof window.localStorage.removeItem === 'function') {
                window.localStorage.removeItem('syllableSession')
                allowRetry = false
                loadSettings()
            }
            return
        }
        if (!settings) {
            return
        }
        var parsed
        try {
            parsed = JSON.parse(settings)
        } catch (err) {
            parsed = null
        }
        if (!parsed || typeof parsed !== 'object' || parsed.listening_mode) {
            return
        }
        if (parsed.full_app_title && document.title === 'Web Assistant') {
            document.title = parsed.full_app_title
        }
        if (!window.Syllable) {
            window.Syllable = {}
        }
        if (!window.Syllable.q) {
            window.Syllable.q = []
        }
        window.syllableSettings = parsed
        injectShim(parsed.shim_url)
    }

    var loadSettings = function () {
        var element = document.getElementById('syllable-tag')
        var scriptSrc = element.src
        var forceMobile = element.dataset.mobile === 'true'
        var idx = scriptSrc.indexOf('?id=')
        var tagId = idx > -1 ? scriptSrc.substr(idx + 4) : undefined
        fetchSettings(tagId, forceMobile, onReceiveSettings)
    }

    if (window.document.readyState === 'loading') {
        window.document.addEventListener('DOMContentLoaded', loadSettings)
    } else {
        loadSettings()
    }
})()
