import { ref, onUnmounted } from 'vue'

// Inline confirmation instead of confirm(): first click arms ("Sure?"),
// second click runs it. Browser dialogs can be suppressed (Firefox).
export function useConfirm(timeoutMs = 3000) {
  const pending = ref(null) // currently armed key
  let timer = null

  function armOrRun(key, action) {
    clearTimeout(timer)
    if (pending.value === key) {
      pending.value = null
      action()
    } else {
      pending.value = key
      timer = setTimeout(() => { pending.value = null }, timeoutMs)
    }
  }

  function isArmed(key) {
    return pending.value === key
  }

  function reset() {
    clearTimeout(timer)
    pending.value = null
  }

  onUnmounted(() => clearTimeout(timer))

  return { pending, isArmed, armOrRun, reset }
}
