import assert from 'node:assert/strict'
import test from 'node:test'
import { effectScope, nextTick, ref } from 'vue'

import { useMinimumVisibleState } from '../src/composables/useMinimumVisibleState.js'

function wait(ms) {
  return new Promise((resolve) => globalThis.setTimeout(resolve, ms))
}

test('minimum visible state stays visible after a fast loading toggle', async () => {
  const scope = effectScope()
  const state = scope.run(() => {
    const loading = ref(false)
    const visible = useMinimumVisibleState(loading, { minVisibleMs: 35 })
    return { loading, visible }
  })

  state.loading.value = true
  await nextTick()
  assert.equal(state.visible.value, true)

  state.loading.value = false
  await nextTick()
  assert.equal(state.visible.value, true)

  await wait(50)
  assert.equal(state.visible.value, false)
  scope.stop()
})

test('minimum visible state cancels a pending hide when loading restarts', async () => {
  const scope = effectScope()
  const state = scope.run(() => {
    const loading = ref(false)
    const visible = useMinimumVisibleState(loading, { minVisibleMs: 40 })
    return { loading, visible }
  })

  state.loading.value = true
  await nextTick()
  state.loading.value = false
  await nextTick()
  await wait(10)

  state.loading.value = true
  await nextTick()
  await wait(40)
  assert.equal(state.visible.value, true)

  state.loading.value = false
  await nextTick()
  await wait(50)
  assert.equal(state.visible.value, false)
  scope.stop()
})
