import { ref, shallowRef } from 'vue'

const visible = ref(false)
const message = shallowRef('')
const _queue = []  // FIFO of pending { resolve, reject }

export function useConfirmState() {
  return { visible, message }
}

/**
 * Show a confirm dialog. Returns a Promise<boolean>.
 * true  → user confirmed (YES)
 * false → user cancelled (NO / backdrop)
 */
export function useConfirm() {
  return function confirm(msg) {
    message.value = msg
    visible.value = true
    return new Promise(resolve => {
      _queue.push(resolve)
    })
  }
}

export function _confirmResolve(result) {
  visible.value = false
  const resolve = _queue.shift()
  resolve?.(result)
  if (_queue.length === 0) {
    visible.value = false
  }
}
