type ExitUiHandler = Readonly<{
  isBusy: () => boolean
  showConfirm: () => void
}>

let exitNow: (() => void) | null = null
let uiHandler: ExitUiHandler | null = null

export function setExitNow(fn: (() => void) | null): void {
  exitNow = fn
}

export function registerExitUiHandler(
  handler: ExitUiHandler | null,
): () => void {
  uiHandler = handler
  return () => {
    if (uiHandler === handler)
      uiHandler = null
  }
}

export function requestExit(): void {
  const handler = uiHandler
  if (handler && handler.isBusy()) {
    handler.showConfirm()
    return
  }
  exitNow?.()
}

export function exitImmediately(): void {
  exitNow?.()
}
