// A tiny leave-guard registry. Views with unsaved edits register two
// functions: one that asks the user (returns false to stay) and one that only
// reports dirtiness for the beforeunload prompt.
type LeaveGuard = () => boolean
type DirtyCheck = () => boolean

let guard: LeaveGuard | null = null
let dirty: DirtyCheck | null = null

export function setLeaveGuard(fn: LeaveGuard, isDirty?: DirtyCheck) {
  guard = fn
  dirty = isDirty ?? null
}

export function clearLeaveGuard(fn?: LeaveGuard) {
  if (!fn || guard === fn) {
    guard = null
    dirty = null
  }
}

export function canLeave(): boolean {
  if (!guard) return true
  try {
    return guard()
  } catch {
    return true
  }
}

export function hasUnsaved(): boolean {
  try {
    return !!dirty && dirty()
  } catch {
    return false
  }
}
