sentReferrerToIframe = false

function loadPaymentPopup () {
  // the below will be replaced with an environment variable from python
  const url = "https://donate.otwarteklatki.pl";
    const params = new URLSearchParams({
        'widget-version': 'multi-option',
        'runAbTest': '',
        'abTest': 'v1'
    });
    const htmlUrl = `${url}/html/embed?${params.toString()}`;
    const cssUrl = url + "/css/embed"

  addStyles()
  addLoadingIcon()

  loadContent(htmlUrl, 'paymentsWidgetPopUp').then(() => {
    const triggerPopUp = document.querySelectorAll('.triggerPopUp')
    const popUpClose = document.querySelector('.popUpClose') ? document.querySelector('.popUpClose') : document.querySelector('.popUpCloseFullScreen')
    const nagPopUp = document.querySelector('.nagPopUp')
    const paymentsPopUp = document.querySelector('.paymentsPopUp') ? document.querySelector('.paymentsPopUp') : document.querySelector('.paymentsPopUpFullScreen')
    const readyToDonateNagButton = document.querySelector('.readyToDonateNagButton')
    const notTodayNagButton = document.querySelector('.notTodayNagButton')
    const preIframeAmountBox = document.getElementById('preIframeAmountBox')
    const embedButtons = document.querySelectorAll('.embed-button')

    addParamsToIframeIfExist('guid, thankyou')

    // return if container is not populated with html
    if (document.getElementById('paymentsWidgetPopUp').children.length <= 1) return

    triggerPopUp.forEach(item => {
      item.addEventListener('click', () => {
        gatherAndSendEmbeddedAmountToIframeIfExists()
        postABTestToIframe()
        postReferrerToIframe()
        fadeOut(nagPopUp)
        fadeIn(paymentsPopUp)
      })
    })

    popUpClose.addEventListener('click', () => {
      fadeOut(paymentsPopUp)
      if (!window.donatedSuccessfully) {
        fadeIn(nagPopUp)
      }
      refreshIframe()
    })

    readyToDonateNagButton.addEventListener('click', () => {
      gatherAndSendEmbeddedAmountToIframeIfExists()
      postABTestToIframe()
      fadeOut(nagPopUp)
      fadeIn(paymentsPopUp)
    })

    notTodayNagButton.addEventListener('click', () => {
      fadeOut(nagPopUp)
    })

    window.addEventListener('message', receiveMessageFromIframe, false)
    preIframeAmountBox.addEventListener('keypress', embedAmountInputChange)
    preIframeAmountBox.addEventListener('change', embedAmountInputChange)
    embedButtons.forEach(button => {
      button.addEventListener('click', selectEmbedButton)
    })
  })

  function addStyles () {
    if (document.querySelector("link[href='" + cssUrl + "']")) return
    const cssLink = document.createElement('link')
    cssLink.setAttribute('rel', 'preload')
    cssLink.setAttribute('as', 'style')
    cssLink.setAttribute('href', cssUrl)
    cssLink.onload = function () {
      cssLink.setAttribute('rel', 'stylesheet')
    }
    document.head.appendChild(cssLink)
  }

  function addLoadingIcon () {
    const paymentsWidgetPopUp = document.getElementById('paymentsWidgetPopUp')
    const popupLoadingRing = document.createElement('div')
    popupLoadingRing.setAttribute('class', 'donationPopUpLoadingRing')
    paymentsWidgetPopUp.appendChild(popupLoadingRing)
  }

  function addParamsToIframeIfExist (params) {
    const iframe = document.getElementById('donationIframe')
    if (!iframe) return
    const paramsToAdd = params.replace(' ', '').split(',')
    let firstParam = true
    paramsToAdd.forEach((item, i) => {
      let param = getParam(item)
      if (param !== null) {
        let operator = firstParam ? "?" : "&"
        firstParam = false
        iframe.src += operator + item + "=" + param
      }
    })
  }

  function getParam (param) {
    const scripts = document.getElementsByTagName('script')
    for (const script of scripts) {
      if (script.getAttribute('id') === 'paymentsWidgetPopUpLoader') {
        return script.getAttribute(param)
      }
    }
    return null
  }

  function receiveMessageFromIframe (event) {
    if (!event.origin.includes('http://localhost:8080') && !event.origin.includes('https://staging.donate.otwarteklatki.pl') && !event.origin.includes('https://donate.otwarteklatki.pl')) {
        return;
    }

    if (event.data === 'donated') {
      window.donatedSuccessfully = true
    }

    if (event.data.pageHeight) {
      const widgetMobileVersionWidth = 620;
      let width = getWidth();
      let iframeContainer = document.getElementById('popUpIframeContainer');
      if (width <= widgetMobileVersionWidth || screen.height <= event.data.pageHeight || wouldNewIframeHeightPutItOffScreen(event.data.pageHeight)) {
        iframeContainer.style.height =  100 + "%";
      } else {
        updateIframeHeight(event.data.pageHeight, iframeContainer)
      }
    }

    if (event.data.v1 && event.data.v1.pageHeight) {
      let iframeContainer = document.getElementById('donationIframe');
      let height = event.data.v1.pageHeight;
      if (height < 265) {
        height = 265;
      }
      iframeContainer.style.height = height + "px";
    }

    if (event.data.closePopUp) {
      const popUpClose = document.querySelector('.popUpClose') ? document.querySelector('.popUpClose') : document.querySelector('.popUpCloseFullScreen');
      popUpClose.click();
    }
    
  }

  function wouldNewIframeHeightPutItOffScreen(iframeHeight) {
    let percentToGet = 5;
    let fivePercentOfScreenHeight = (percentToGet / 100) * screen.height;
    return (screen.height + fivePercentOfScreenHeight) < iframeHeight;
  }

  function updateIframeHeight(pageHeight, iframeContainer) {
    let newHeight = pageHeight + 40
    iframeContainer.style.height = newHeight + "px"
  }
  
  function gatherAndSendEmbeddedAmountToIframeIfExists() {
    const amount = preIframeAmountBox.value
    if (amount) {
      postAmountToIframe(amount)
    }
  }

  function postABTestToIframe () {
    const amount = { 'abTest': 'v1' }
    const iframeWindow = document.getElementById('donationIframe').contentWindow
    iframeWindow.postMessage(amount, '*')
  }

  function postAmountToIframe (message) {
    const amount = { 'amount': message }
    const iframeWindow = document.getElementById('donationIframe').contentWindow
    iframeWindow.postMessage(amount, '*')
  }

  function postReferrerToIframe () {
    if (!sentReferrerToIframe) {
      const message = { 'referrer': document.referrer }
      const iframeWindow = document.getElementById('donationIframe').contentWindow
      iframeWindow.postMessage(message, '*')
    }
    sentReferrerToIframe = true
  }

  function refreshIframe () {
    const iframe = document.getElementById('donationIframe')
    iframe.src = iframe.src
    if (window.donatedSuccessfully === true) {
      window.donatedSuccessfully = false
    }
  }

  async function loadContent (url, el) {
    const contentEl = document.getElementById(el)
    contentEl.innerHTML = await fetchHtmlAsText(url)
  }

  async function fetchHtmlAsText (url) {
    const response = await fetch(url)
    return await response.text()
  }

  function embedAmountInputChange (event) {
    document.querySelectorAll('.embed-button-group .embed-button').forEach(item => {
      item.classList.remove('selected')
    })
    return isNumber(event)
  }

  function selectEmbedButton (event) {
    const el = event.target
    document.querySelectorAll('.embed-button-group .embed-button').forEach(item => {
      item.classList.remove('selected')
    })
    el.classList.add('selected')
    updateAmountBox(el.innerText)
  }

  function updateAmountBox (message) {
    preIframeAmountBox.value = stripCurrency(message)
  }

  function stripCurrency (amount) {
    // get currencycode from flask text locale variable
    const currencySymbol = "zł"
    return amount.replace(' ' + currencySymbol, '').replace(currencySymbol + ' ', '')
  }

  function isNumber (e) {
    const charCode = e.which ? e.which : e.keyCode
    return /\d/.test(String.fromCharCode(charCode))
  }

  function fadeOut (el) {
    el.style.opacity = 1
    function fade () {
      el.style.opacity -= 0.1
      if (el.style.opacity < 0) {
        el.style.display = 'none'
      } else {
        requestAnimationFrame(fade)
      }
    }
    fade()
  }

  function fadeIn (el, display) {
    el.style.opacity = 0
    el.style.display = display || 'block'
    function fade () {
      let opacity = parseFloat(el.style.opacity)
      opacity += 0.1
      if (opacity <= 1) {
        el.style.opacity = opacity
        requestAnimationFrame(fade)
      }
    }
    fade()
  }

  function getWidth() {
    return Math.max(
      document.body.scrollWidth,
      document.documentElement.scrollWidth,
      document.body.offsetWidth,
      document.documentElement.offsetWidth,
      document.documentElement.clientWidth
    );
  }
}

window.onload = loadPaymentPopup