import { render, screen } from '@testing-library/react'
import { beforeEach, describe, expect, it, vi } from 'vitest'
import { useBackendVersion } from '@/hooks/useVersion'
import AboutPage from '@/pages/About'

vi.mock('@/hooks/useVersion', () => ({
  useBackendVersion: vi.fn(),
}))

vi.mock('@/constants/app', () => ({
  APP_NAME: 'Nex',
  APP_DESCRIPTION: 'AI Gateway - 统一的大模型 API 网关',
  APP_WEBSITE: 'https://github.com/nex/gateway',
  APP_VERSION: '0.1.0',
}))

const mockUseBackendVersion = useBackendVersion as ReturnType<typeof vi.fn>

describe('AboutPage', () => {
  beforeEach(() => {
    mockUseBackendVersion.mockReturnValue({
      data: { version: '0.1.0', commit: 'abc1234', buildTime: '2026-05-05T00:00:00Z' },
      isError: false,
      isLoading: false,
    } as ReturnType<typeof useBackendVersion>)
  })

  it('renders brand, description and links', () => {
    render(<AboutPage />)

    expect(screen.getByRole('heading', { name: 'Nex' })).toBeInTheDocument()
    expect(screen.getByText('AI Gateway - 统一的大模型 API 网关')).toBeInTheDocument()
    expect(screen.getByText('GitHub')).toHaveAttribute('href', 'https://github.com/nex/gateway')
  })

  it('shows frontend and backend versions', () => {
    render(<AboutPage />)

    expect(screen.getByText('前端版本')).toBeInTheDocument()
    expect(screen.getAllByText('0.1.0').length).toBeGreaterThan(0)
    expect(screen.getByText('abc1234')).toBeInTheDocument()
    expect(screen.getByText('2026-05-05T00:00:00Z')).toBeInTheDocument()
  })

  it('shows matched status', () => {
    render(<AboutPage />)

    expect(screen.getByText('版本一致')).toBeInTheDocument()
  })

  it('shows mismatched status', () => {
    mockUseBackendVersion.mockReturnValue({
      data: { version: '0.2.0', commit: 'abc1234', buildTime: '2026-05-05T00:00:00Z' },
      isError: false,
      isLoading: false,
    } as ReturnType<typeof useBackendVersion>)

    render(<AboutPage />)

    expect(screen.getByText('版本不一致')).toBeInTheDocument()
    expect(screen.getByText(/用于部署诊断/)).toBeInTheDocument()
  })

  it('shows unknown status for dev backend version', () => {
    mockUseBackendVersion.mockReturnValue({
      data: { version: 'dev', commit: 'unknown', buildTime: 'unknown' },
      isError: false,
      isLoading: false,
    } as ReturnType<typeof useBackendVersion>)

    render(<AboutPage />)

    expect(screen.getByText('无法判断版本')).toBeInTheDocument()
  })

  it('shows unavailable status on backend request failure', () => {
    mockUseBackendVersion.mockReturnValue({
      data: undefined,
      isError: true,
      isLoading: false,
    } as ReturnType<typeof useBackendVersion>)

    render(<AboutPage />)

    expect(screen.getByText('无法获取后端版本')).toBeInTheDocument()
    expect(screen.getByText(/后端版本接口暂时不可用/)).toBeInTheDocument()
  })
})
