import { getCurrentScope, onScopeDispose, ref } from 'vue'

export const useDebouncedCallback = <Args extends unknown[]>(
  callback: (...args: Args) => void,
  delay: number
) => {
  const timeout = ref<ReturnType<typeof setTimeout>>()
  const debouncedFn = (...args: Args) => {
    const handler = () => {
      clearTimeout(timeout.value)
      callback(...args)
    }

    clearTimeout(timeout.value)
    timeout.value = setTimeout(handler, delay)
  }

  // Mirror VueUse's tryOnScopeDispose: register the cleanup only when called
  // inside an active effect scope (a component setup). Calling it outside one
  // is then a no-op instead of emitting a "no active effect scope" warning.
  if (getCurrentScope()) {
    onScopeDispose(() => clearTimeout(timeout.value))
  }

  return debouncedFn
}
