import type { Ref } from 'vue'

export function useUnsavedGuard(isDirty: Ref<boolean>) {
  const { confirm } = useConfirm()

  function handleBeforeUnload(e: BeforeUnloadEvent) {
    if (isDirty.value) {
      e.preventDefault()
      e.returnValue = ''
    }
  }

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

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

  onBeforeRouteLeave(async () => {
    if (!isDirty.value) return true
    const ok = await confirm({
      title: 'Modifications non sauvegardées',
      message: 'Vous avez des modifications en cours. Voulez-vous quitter sans sauvegarder ?',
      confirmText: 'Quitter sans sauver',
      cancelText: 'Rester',
      dangerous: true,
    })
    return ok
  })
}
