import type { Ref } from 'vue'
import { getCurrentInstance, onBeforeUnmount, ref } from 'vue'

export type TimedToast = Readonly<{
  visible: Ref<boolean>
  text: Ref<string>
  show: (text: string, durationMs?: number | null) => void
  hide: () => void
}>

/**
 * Small timed toast state helper for the TUI.
 *
 * This is intentionally minimal: callers own how/where the toast is rendered.
 */
export function useTimedToast(
  durationMs = 1200,
  onChange?: () => void,
): TimedToast {
  const visible = ref(false)
  const text = ref('')
  let timer: ReturnType<typeof setTimeout> | null = null

  const hide = () => {
    visible.value = false
    if (timer) clearTimeout(timer)
    timer = null
    onChange?.()
  }

  const show = (nextText: string, overrideDurationMs?: number | null) => {
    text.value = String(nextText ?? '')
    visible.value = true
    if (timer) clearTimeout(timer)
    onChange?.()
    if (overrideDurationMs === null) {
      timer = null
      return
    }
    const resolvedDuration =
      typeof overrideDurationMs === 'number' &&
      Number.isFinite(overrideDurationMs)
        ? overrideDurationMs
        : durationMs
    timer = setTimeout(
      () => {
        visible.value = false
        timer = null
        onChange?.()
      },
      Math.max(0, resolvedDuration),
    )
  }

  if (getCurrentInstance()) {
    onBeforeUnmount(() => {
      hide()
    })
  }

  return { visible, text, show, hide } as const
}
