import { describe, it, expect, vi } from 'vitest'
import { render, screen } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { Provider } from 'react-redux'
import { MemoryRouter, Routes, Route } from 'react-router-dom'
import { configureStore } from '@reduxjs/toolkit'
import authReducer from '../store/slices/authSlice'
import tabsReducer from '../store/slices/tabsSlice'
import NavOverlay from '../components/NavOverlay'

function makeStore() {
  return configureStore({ reducer: { auth: authReducer, tabs: tabsReducer } })
}

function renderOverlay(onClose = vi.fn()) {
  return render(
    <Provider store={makeStore()}>
      <MemoryRouter initialEntries={['/']}>
        <Routes>
          <Route path="/" element={<NavOverlay onClose={onClose} />} />
          <Route path="/usr/users" element={<div>UserList</div>} />
        </Routes>
      </MemoryRouter>
    </Provider>
  )
}

describe('NavOverlay', () => {
  it('renders_systemModules', () => {
    renderOverlay()
    expect(screen.getByText('系统设置')).toBeInTheDocument()
    expect(screen.getByText('用户管理')).toBeInTheDocument()
  })

  it('clickUserList_navigatesAndClosesOverlay', async () => {
    const onClose = vi.fn()
    renderOverlay(onClose)
    await userEvent.click(screen.getByText('用户列表'))
    expect(screen.getByText('UserList')).toBeInTheDocument()
    expect(onClose).toHaveBeenCalledTimes(1)
  })

  it('clickBackground_callsOnClose', async () => {
    const onClose = vi.fn()
    render(
      <Provider store={makeStore()}>
        <MemoryRouter>
          <NavOverlay onClose={onClose} />
        </MemoryRouter>
      </Provider>
    )
    // Click the outer overlay div (background)
    await userEvent.click(document.querySelector('[data-testid="nav-bg"]')!)
    expect(onClose).toHaveBeenCalledTimes(1)
  })
})
