import { describe, it, expect, vi, beforeEach } from 'vitest'
import { render, screen } from '@testing-library/react'
import PermissionGuard from '@/components/PermissionGuard'

vi.mock('@/stores/usePermissionStore', () => ({
  usePermissionStore: vi.fn(),
}))

import { usePermissionStore } from '@/stores/usePermissionStore'

const mockUsePermissionStore = vi.mocked(usePermissionStore)

describe('PermissionGuard', () => {
  beforeEach(() => {
    vi.clearAllMocks()
  })

  it('should render children when user has permission', () => {
    mockUsePermissionStore.mockImplementation((selector: any) =>
      selector({ hasPermission: (p: string) => p === 'system:user:list', hasRole: () => false })
    )
    render(
      <PermissionGuard permission="system:user:list">
        <div>Protected Content</div>
      </PermissionGuard>
    )
    expect(screen.getByText('Protected Content')).toBeInTheDocument()
  })

  it('should render fallback when user lacks permission', () => {
    mockUsePermissionStore.mockImplementation((selector: any) =>
      selector({ hasPermission: () => false, hasRole: () => false })
    )
    render(
      <PermissionGuard permission="system:user:list" fallback={<div>No Access</div>}>
        <div>Protected Content</div>
      </PermissionGuard>
    )
    expect(screen.queryByText('Protected Content')).not.toBeInTheDocument()
    expect(screen.getByText('No Access')).toBeInTheDocument()
  })

  it('should render null fallback by default when no permission', () => {
    mockUsePermissionStore.mockImplementation((selector: any) =>
      selector({ hasPermission: () => false, hasRole: () => false })
    )
    const { container } = render(
      <PermissionGuard permission="system:user:list">
        <div>Protected Content</div>
      </PermissionGuard>
    )
    expect(container.innerHTML).toBe('')
  })

  it('should check role when type is role', () => {
    mockUsePermissionStore.mockImplementation((selector: any) =>
      selector({ hasPermission: () => false, hasRole: (r: string) => r === 'admin' })
    )
    render(
      <PermissionGuard role="admin" type="role">
        <div>Admin Content</div>
      </PermissionGuard>
    )
    expect(screen.getByText('Admin Content')).toBeInTheDocument()
  })

  it('should render children when no permission or role specified', () => {
    mockUsePermissionStore.mockImplementation((selector: any) =>
      selector({ hasPermission: () => false, hasRole: () => false })
    )
    render(
      <PermissionGuard>
        <div>Always Visible</div>
      </PermissionGuard>
    )
    expect(screen.getByText('Always Visible')).toBeInTheDocument()
  })
})
