const WIDGET_URL = 'https://halo.bca.co.id/buzz-widget-new/'
const ORIGIN = 'https://halo.bca.co.id'

;(function docReadyChecker(funcName, baseObj) {
  const funcNameValue = funcName || 'docReady'
  const baseObjValue = baseObj || window
  var readyList = []
  var readyFired = false
  var readyEventHandlersInstalled = false

  function ready() {
    if (!readyFired) {
      readyFired = true
      for (var i = 0; i < readyList.length; i++) {
        readyList[i].fn.call(window, readyList[i].ctx)
      }
      readyList = []
    }
  }

  function readyStateChange() {
    if (document.readyState === 'complete') {
      ready()
    }
  }

  baseObjValue[funcNameValue] = function runDocReadyCallback(
    callback,
    context
  ) {
    if (readyFired) {
      setTimeout(function() {
        callback(context)
      }, 1)
      return
    }
    readyList.push({ fn: callback, ctx: context })
    if (document.readyState === 'complete') {
      setTimeout(ready, 1)
    } else if (!readyEventHandlersInstalled) {
      if (document.addEventListener) {
        document.addEventListener('DOMContentLoaded', ready, false)
        window.addEventListener('load', ready, false)
      } else {
        document.attachEvent('onreadystatechange', readyStateChange)
        window.attachEvent('onload', ready)
      }
      readyEventHandlersInstalled = true
    }
  }
})('docReady', window)

function listener(event) {
  if (ORIGIN === event.origin) {
    if (event.data.hasOwnProperty('buzzCounter')) {
      const sanitizedData = event.data.buzzCounter

      if (isNaN(sanitizedData)) {
        return
      }

      document.getElementById('buzz-counter').innerHTML = sanitizedData
      if (parseInt(sanitizedData) > 0) {
        document.getElementById('buzz-counter').style.display = 'inline-block'
      } else {
        document.getElementById('buzz-counter').style.display = 'none'
      }
    }
  }
}

if (window.addEventListener) {
  addEventListener('message', listener, false)
} else {
  attachEvent('onmessage', listener)
}

function embedBuzz() {
  const scriptName = document.getElementById('buzz-script')
  const lang = scriptName.getAttribute('data-language') === 'en' ? 'en' : ''
  const buzz = document.getElementById('buzz')
  const iframe = document.createElement('IFRAME')
  const dataUser = buzz.dataset.user
  const dataUserParam = dataUser ? '?data=' + encodeURIComponent(dataUser) : ''
  const frameURL = WIDGET_URL + '#/' + lang + dataUserParam
  iframe.id = 'buzz-frame'
  iframe.src = frameURL
  iframe.style.backgroundColor = 'transparent'
  iframe.style.border = 'none'
  iframe.style.verticalAlign = 'text-bottom'
  iframe.style.position = 'relative'
  iframe.style.width = '100%'
  iframe.style.height = '100%'
  iframe.style.margin = '0px'
  iframe.style.display = 'block'
  buzz.appendChild(iframe)
}

docReady(embedBuzz)
