import { ref, onMounted, onUnmounted } from 'vue'

const MOBILE_BREAKPOINT = 768

const isMobile = ref(false)
let listenerCount = 0

function update() {
  isMobile.value = window.innerWidth < MOBILE_BREAKPOINT
}

export function useDevice() {
  onMounted(() => {
    if (listenerCount === 0) {
      update()
      window.addEventListener('resize', update)
    }
    listenerCount++
  })

  onUnmounted(() => {
    listenerCount--
    if (listenerCount === 0) {
      window.removeEventListener('resize', update)
    }
  })

  return { isMobile }
}
