import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"
import { act, renderHook } from "@testing-library/react"
import { useCurrentTime } from "./use-current-time"

describe("useCurrentTime", () => {
  beforeEach(() => {
    vi.useFakeTimers()
  })

  afterEach(() => {
    vi.useRealTimers()
  })

  it("returns a Date on initial render", () => {
    const { result } = renderHook(() => useCurrentTime(60000))
    expect(result.current).toBeInstanceOf(Date)
  })

  it("updates after the specified interval", () => {
    const initialTime = new Date(2026, 0, 1, 10, 0, 0)
    vi.setSystemTime(initialTime)

    const { result } = renderHook(() => useCurrentTime(60000))
    expect(result.current.getTime()).toBe(initialTime.getTime())

    act(() => {
      vi.advanceTimersByTime(60000)
    })

    const expectedTime = new Date(2026, 0, 1, 10, 1, 0)
    expect(result.current.getTime()).toBe(expectedTime.getTime())
  })

  it("clears interval on unmount", () => {
    const { unmount } = renderHook(() => useCurrentTime(60000))
    const clearIntervalSpy = vi.spyOn(global, "clearInterval")
    unmount()
    expect(clearIntervalSpy).toHaveBeenCalled()
  })
})
