import type { ReactNode } from 'react'
import { renderHook } from '@testing-library/react'
import { MemoryRouter } from 'react-router-dom'
import { describe, expect, it } from 'vitest'

import { useBreadcrumbs } from './useBreadcrumbs'

function createWrapper(pathname: string) {
  return function Wrapper({ children }: { children: ReactNode }) {
    return <MemoryRouter initialEntries={[pathname]}>{children}</MemoryRouter>
  }
}

describe('useBreadcrumbs', () => {
  it('returns an empty breadcrumb list at the root path', () => {
    const { result } = renderHook(() => useBreadcrumbs(), {
      wrapper: createWrapper('/'),
    })

    expect(result.current).toEqual([])
  })

  it('maps known single-segment routes to a terminal breadcrumb item', () => {
    const { result } = renderHook(() => useBreadcrumbs(), {
      wrapper: createWrapper('/dashboard'),
    })

    expect(result.current).toEqual([
      {
        title: '概览',
        path: undefined,
      },
    ])
  })

  it('builds nested breadcrumbs for supported child routes', () => {
    const { logsResult } = {
      logsResult: renderHook(() => useBreadcrumbs(), {
        wrapper: createWrapper('/logs/login'),
      }),
    }

    expect(logsResult.result.current).toEqual([
      {
        title: '审计日志',
        path: '/logs',
      },
      {
        title: '登录日志',
        path: undefined,
      },
    ])

    const profileResult = renderHook(() => useBreadcrumbs(), {
      wrapper: createWrapper('/profile/security'),
    })

    expect(profileResult.result.current).toEqual([
      {
        title: '个人资料',
        path: '/profile',
      },
      {
        title: '安全设置',
        path: undefined,
      },
    ])
  })

  it('skips unknown route segments while keeping known ancestors', () => {
    const { result } = renderHook(() => useBreadcrumbs(), {
      wrapper: createWrapper('/logs/unknown'),
    })

    expect(result.current).toEqual([
      {
        title: '审计日志',
        path: '/logs',
      },
    ])
  })
})
