import { onMounted, onUnmounted, toValue, type MaybeRefOrGetter } from 'vue'

export function useUnsavedChangesWarning(hasUnsavedChanges: MaybeRefOrGetter<boolean>) {
  const handleBeforeUnload = (event: BeforeUnloadEvent) => {
    if (!toValue(hasUnsavedChanges)) return
    event.preventDefault()
    event.returnValue = ''
  }

  onMounted(() => {
    window.addEventListener('beforeunload', handleBeforeUnload)
  })

  onUnmounted(() => {
    window.removeEventListener('beforeunload', handleBeforeUnload)
  })
}
