import { describe, it, expect } from 'vitest';
import { reducer, toast } from './use-toast';

describe('use-toast reducer', () => {
  const emptyState = { toasts: [] };

  it('adds a toast with ADD_TOAST action', () => {
    const newToast = { id: '1', title: 'Test', open: true } as any;
    const result = reducer(emptyState, {
      type: 'ADD_TOAST',
      toast: newToast,
    });
    expect(result.toasts).toHaveLength(1);
    expect(result.toasts[0].title).toBe('Test');
  });

  it('limits toasts to TOAST_LIMIT (1)', () => {
    const toast1 = { id: '1', title: 'First', open: true } as any;
    const toast2 = { id: '2', title: 'Second', open: true } as any;

    let state = reducer(emptyState, { type: 'ADD_TOAST', toast: toast1 });
    state = reducer(state, { type: 'ADD_TOAST', toast: toast2 });

    expect(state.toasts).toHaveLength(1);
    expect(state.toasts[0].title).toBe('Second');
  });

  it('updates a toast with UPDATE_TOAST action', () => {
    const initial = { id: '1', title: 'Old', open: true } as any;
    const state = reducer(emptyState, { type: 'ADD_TOAST', toast: initial });

    const result = reducer(state, {
      type: 'UPDATE_TOAST',
      toast: { id: '1', title: 'Updated' },
    });
    expect(result.toasts[0].title).toBe('Updated');
  });

  it('dismisses a toast by id', () => {
    const initial = { id: '1', title: 'Test', open: true } as any;
    const state = reducer(emptyState, { type: 'ADD_TOAST', toast: initial });

    const result = reducer(state, { type: 'DISMISS_TOAST', toastId: '1' });
    expect(result.toasts[0].open).toBe(false);
  });

  it('removes a toast by id', () => {
    const initial = { id: '1', title: 'Test', open: true } as any;
    const state = reducer(emptyState, { type: 'ADD_TOAST', toast: initial });

    const result = reducer(state, { type: 'REMOVE_TOAST', toastId: '1' });
    expect(result.toasts).toHaveLength(0);
  });

  it('removes all toasts when no id provided', () => {
    const initial = { id: '1', title: 'Test', open: true } as any;
    const state = reducer(emptyState, { type: 'ADD_TOAST', toast: initial });

    const result = reducer(state, { type: 'REMOVE_TOAST', toastId: undefined });
    expect(result.toasts).toHaveLength(0);
  });
});

describe('toast function', () => {
  it('returns an object with id, dismiss, and update', () => {
    const result = toast({ title: 'Hello' } as any);
    expect(result).toHaveProperty('id');
    expect(typeof result.id).toBe('string');
    expect(typeof result.dismiss).toBe('function');
    expect(typeof result.update).toBe('function');
  });

  it('generates unique ids for each toast', () => {
    const t1 = toast({ title: 'First' } as any);
    const t2 = toast({ title: 'Second' } as any);
    expect(t1.id).not.toBe(t2.id);
  });
});
