import { computed, onBeforeUnmount, onMounted, ref } from 'vue'

export function useKbxNetworkState() {
  const online = ref(typeof navigator === 'undefined' ? true : navigator.onLine)

  const refresh = () => {
    online.value = navigator.onLine
  }

  onMounted(() => {
    window.addEventListener('online', refresh)
    window.addEventListener('offline', refresh)
  })

  onBeforeUnmount(() => {
    window.removeEventListener('online', refresh)
    window.removeEventListener('offline', refresh)
  })

  return {
    online: computed(() => online.value),
  }
}
