import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
import { setActivePinia, createPinia } from 'pinia'
import { useToastStore } from '@/stores/toast'

describe('toast store', () => {
  beforeEach(() => {
    setActivePinia(createPinia())
    vi.useFakeTimers()
  })

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

  it('show adds a message to toasts', () => {
    const store = useToastStore()
    store.show('Hello!')

    expect(store.toasts).toHaveLength(1)
    expect(store.toasts[0].message).toBe('Hello!')
    expect(store.toasts[0].type).toBe('info')
  })

  it('show with explicit type sets correct type', () => {
    const store = useToastStore()
    store.show('Saved', 'success')

    expect(store.toasts[0].type).toBe('success')
  })

  it('show with error type sets error type', () => {
    const store = useToastStore()
    store.show('Something broke', 'error')

    expect(store.toasts[0].type).toBe('error')
  })

  it('multiple show calls add multiple toasts', () => {
    const store = useToastStore()
    store.show('First')
    store.show('Second')

    expect(store.toasts).toHaveLength(2)
  })

  it('auto-dismisses after 2500ms', () => {
    const store = useToastStore()
    store.show('Temporary')

    expect(store.toasts).toHaveLength(1)

    vi.advanceTimersByTime(2500)

    expect(store.toasts).toHaveLength(0)
  })

  it('does not dismiss before 2500ms', () => {
    const store = useToastStore()
    store.show('Temporary')

    vi.advanceTimersByTime(2499)

    expect(store.toasts).toHaveLength(1)
  })

  it('dismiss removes a specific toast by id', () => {
    const store = useToastStore()
    store.show('First')
    store.show('Second')

    const id = store.toasts[0].id
    store.dismiss(id)

    expect(store.toasts).toHaveLength(1)
    expect(store.toasts[0].message).toBe('Second')
  })

  it('dismiss with unknown id does nothing', () => {
    const store = useToastStore()
    store.show('Msg')
    store.dismiss(99999)

    expect(store.toasts).toHaveLength(1)
  })

  it('each toast gets a unique id', () => {
    const store = useToastStore()
    store.show('A')
    store.show('B')
    store.show('C')

    const ids = store.toasts.map(t => t.id)
    const uniqueIds = new Set(ids)
    expect(uniqueIds.size).toBe(3)
  })
})
