import { render, screen, fireEvent, act } from '@testing-library/react'
import { MemoryRouter } from 'react-router-dom'
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
import { cartAdded, cartDismissed } from '@/shared/model/cart-notifications'
import { CartSnackbar } from '@/shared/ui/CartSnackbar'

const navigateMock = vi.fn()

vi.mock('react-router-dom', async (importOriginal) => {
  const mod = await importOriginal<typeof import('react-router-dom')>()
  return { ...mod, useNavigate: () => navigateMock }
})

beforeEach(() => {
  navigateMock.mockClear()
})

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

function renderWithRouter() {
  render(
    <MemoryRouter initialEntries={['/']}>
      <CartSnackbar />
    </MemoryRouter>,
  )
}

describe('CartSnackbar', () => {
  it('is hidden when store is false', () => {
    cartDismissed()
    renderWithRouter()
    expect(screen.queryByText(/товар добавлен/i)).not.toBeInTheDocument()
  })

  it('shows snackbar when cartAdded is fired', () => {
    renderWithRouter()
    cartAdded()
    expect(screen.getByText(/товар добавлен/i)).toBeInTheDocument()
    expect(screen.getByRole('button', { name: /перейти в корзину/i })).toBeInTheDocument()
  })

  it('closes on dismiss button click', () => {
    renderWithRouter()
    cartAdded()
    const closeBtn = screen.getByLabelText(/закрыть/i)
    fireEvent.click(closeBtn)
    expect(screen.queryByText(/товар добавлен/i)).not.toBeInTheDocument()
  })

  it('auto-closes after 4 seconds', () => {
    vi.useFakeTimers()
    renderWithRouter()
    cartAdded()
    act(() => {
      vi.advanceTimersByTime(4000)
    })
    expect(screen.queryByText(/товар добавлен/i)).not.toBeInTheDocument()
  })

  it('navigates to /cart and closes on "Перейти в корзину" click', () => {
    renderWithRouter()
    cartAdded()
    fireEvent.click(screen.getByRole('button', { name: /перейти в корзину/i }))
    expect(navigateMock).toHaveBeenCalledWith('/cart')
    expect(screen.queryByText(/товар добавлен/i)).not.toBeInTheDocument()
  })
})
