const screen = () => {
  init()
}

const init = () => {
  addListenners()

  setTimeout(() => {
    scrollAppear()
  }, 100)
  window.dispatchEvent(new Event('resize'))
}
const addListenners = () => {
  window.addEventListener(
    'scroll',
    () => {
      onscroll()
    },
    false
  )

  window.addEventListener(
    'resize',
    () => {
      onresize()
    },
    false
  )
}
const onresize = () => {
  scrollAppear()
}
const onscroll = () => {
  scrollAppear()
}

const scrollAppear = () => {
  const elements = document.querySelectorAll('.scroll-appear')
  const elTemp = document.getElementsByClassName('scroll-appear-temporise')
  let d = 0 + elTemp.length * 100

  if (elements.length > 0) {
    elements.forEach((el) => {
      try {
        if (
          isInViewport(el, -window.innerHeight / 10) &&
          !el.classList.contains('scroll-appear-ok') &&
          !el.classList.contains('scroll-appear-temporise')
        ) {
          setTimeout(() => {
            el.classList.add('scroll-appear-ok')
          }, d)
          d += 100
        } else {
          d = 0
        }
      } catch (error) {
        el.classList.add('scroll-appear-ok')
      }
    })
  }
}

const isInViewport = (el, gap, decal) => {
  const d = decal || 0
  const elY = el.getBoundingClientRect().top + d
  const wY = window.innerHeight
  const g = gap || 0
  return elY < wY + g && elY + el.offsetHeight > 0 - g
}

export { screen }
