import { act } from 'react';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { useCooldownTimer } from '../../src/hooks/useCooldownTimer';
import { renderHook } from '../helpers/renderHook';

describe('useCooldownTimer', () => {
    beforeEach(() => {
        vi.useFakeTimers();
    });

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

    it('decrements cooldown every second while enabled', () => {
        const { result } = renderHook(() => useCooldownTimer(2, true));

        expect(result.current.cooldown).toBe(2);

        act(() => {
            vi.advanceTimersByTime(1000);
        });
        expect(result.current.cooldown).toBe(1);

        act(() => {
            vi.advanceTimersByTime(1000);
        });
        expect(result.current.cooldown).toBe(0);
    });

    it('does not decrement when disabled', () => {
        const { result } = renderHook(() => useCooldownTimer(2, false));

        act(() => {
            vi.advanceTimersByTime(3000);
        });

        expect(result.current.cooldown).toBe(2);
    });

    it('startCooldown floors values and clamps negatives', () => {
        const { result } = renderHook(() => useCooldownTimer(0, true));

        act(() => {
            result.current.startCooldown(2.8);
        });
        expect(result.current.cooldown).toBe(2);

        act(() => {
            result.current.startCooldown(-4);
        });
        expect(result.current.cooldown).toBe(0);
    });

    it('stays at zero when already expired', () => {
        const { result } = renderHook(() => useCooldownTimer(0, true));

        act(() => {
            vi.advanceTimersByTime(2000);
        });

        expect(result.current.cooldown).toBe(0);
    });
});
