// @vitest-environment jsdom
/**
 * Hook test for useToast — showToast sets state, default variant, auto-dismiss
 * after the duration, and a new toast resetting the dismiss timer.
 */
import '../test/dom-setup';
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
import { renderHook, act } from '@testing-library/react';
import { useToast } from './useToast';

beforeEach(() => vi.useFakeTimers());
afterEach(() => vi.useRealTimers());

describe('useToast', () => {
  it('starts with no toast', () => {
    const { result } = renderHook(() => useToast());
    expect(result.current.toast).toBeNull();
  });

  it('shows a toast and defaults variant to success', () => {
    const { result } = renderHook(() => useToast());
    act(() => result.current.showToast('saved'));
    expect(result.current.toast).toEqual({ message: 'saved', variant: 'success' });
  });

  it('honors an explicit error variant', () => {
    const { result } = renderHook(() => useToast());
    act(() => result.current.showToast('boom', 'error'));
    expect(result.current.toast?.variant).toBe('error');
  });

  it('auto-dismisses after the duration', () => {
    const { result } = renderHook(() => useToast(1000));
    act(() => result.current.showToast('hi'));
    expect(result.current.toast).not.toBeNull();
    act(() => vi.advanceTimersByTime(1000));
    expect(result.current.toast).toBeNull();
  });

  it('does not dismiss before the duration elapses', () => {
    const { result } = renderHook(() => useToast(3000));
    act(() => result.current.showToast('hi'));
    act(() => vi.advanceTimersByTime(2999));
    expect(result.current.toast).not.toBeNull();
  });

  it('resets the dismiss timer when a new toast appears', () => {
    const { result } = renderHook(() => useToast(1000));
    act(() => result.current.showToast('first'));
    act(() => vi.advanceTimersByTime(800));
    act(() => result.current.showToast('second'));
    // 800ms after the first would have dismissed it, but the second reset it.
    act(() => vi.advanceTimersByTime(800));
    expect(result.current.toast?.message).toBe('second');
    act(() => vi.advanceTimersByTime(200));
    expect(result.current.toast).toBeNull();
  });
});
