const STYLE = [
  'overflow-y: scroll',
  'width: 100px',
  'height: 100px',
  'position: absolute',
  'top: -9999'
].join('; ')
const DEBOUNCE = 500

function setScrollbarWidthProperty () {
  const div = document.createElement('div')
  div.setAttribute('style', STYLE)
  document.body.appendChild(div)
  const scrollbarWidth = div.offsetWidth - div.clientWidth
  div.remove()

  document.documentElement.style.setProperty('--scrollbar-width', `${scrollbarWidth}px`)
}

export default function updateScrollbarWidth () {
  setScrollbarWidthProperty()

  let resizeId = null
  window.addEventListener('resize', () => {
    clearTimeout(resizeId)
    resizeId = setTimeout(() => {
      setScrollbarWidthProperty()
    }, DEBOUNCE)
  })
}
