import * as React from 'react'

export interface SkeletonGuardProps {
  pending: boolean
  children: React.ReactNode
  delayMs?: number
  minDurationMs?: number
}

const DEFAULT_DELAY_MS = 200
const DEFAULT_MIN_DURATION_MS = 400

export function SkeletonGuard({
  pending,
  children,
  delayMs = DEFAULT_DELAY_MS,
  minDurationMs = DEFAULT_MIN_DURATION_MS,
}: SkeletonGuardProps) {
  const [visible, setVisible] = React.useState(false)
  const shownAtRef = React.useRef<number | null>(null)

  React.useEffect(() => {
    if (pending) {
      if (shownAtRef.current !== null) return undefined

      const delayTimer = globalThis.setTimeout(() => {
        shownAtRef.current = Date.now()
        setVisible(true)
      }, delayMs)

      return () => {
        globalThis.clearTimeout(delayTimer)
      }
    }

    if (shownAtRef.current === null) {
      return undefined
    }

    const remaining = Math.max(0, minDurationMs - (Date.now() - shownAtRef.current))
    const holdTimer = globalThis.setTimeout(() => {
      shownAtRef.current = null
      setVisible(false)
    }, remaining)

    return () => {
      globalThis.clearTimeout(holdTimer)
    }
  }, [pending, delayMs, minDurationMs])

  return visible ? <>{children}</> : null
}
