import { screen } from '@testing-library/react'
import { Route, Routes } from 'react-router-dom'
import { describe, expect, it, vi } from 'vitest'

import WikiDetailPage from '@/pages/wiki/WikiDetailPage'
import { buildTag, buildWikiPage } from '@/test/factories'
import { renderWithProviders } from '@/test/render'

const wikiApi = vi.hoisted (() => ({
  fetchWikiPage:        vi.fn (),
  fetchWikiPageByTitle: vi.fn (),
}))

const tagsApi = vi.hoisted (() => ({
  fetchTagByName: vi.fn (),
}))

const postsApi = vi.hoisted (() => ({
  fetchPosts: vi.fn (),
}))

vi.mock ('@/lib/wiki', () => wikiApi)
vi.mock ('@/lib/tags', () => tagsApi)
vi.mock ('@/lib/posts', () => postsApi)

describe ('WikiDetailPage', () => {
  it ('renders deprecated state outside the wiki title link', async () => {
    wikiApi.fetchWikiPageByTitle.mockResolvedValueOnce (buildWikiPage ({
      title:        '旧タグ',
      deprecatedAt: '2026-06-01T00:00:00.000Z',
    }))
    tagsApi.fetchTagByName.mockResolvedValueOnce (buildTag ({
      name:         '旧タグ',
      deprecatedAt: '2026-06-01T00:00:00.000Z',
    }))
    postsApi.fetchPosts.mockResolvedValueOnce ({ posts: [], count: 0 })

    renderWithProviders (
        <Routes>
          <Route path="/wiki/:title" element={<WikiDetailPage/>}/>
        </Routes>,
        { route: '/wiki/%E6%97%A7%E3%82%BF%E3%82%B0' },
    )

    const marker = await screen.findByText ('（廃止）')
    const heading = marker.closest ('h1')
    const link = screen.getByRole ('link', { name: '旧タグ' })

    expect (heading).not.toBeNull ()
    expect (heading!).toHaveTextContent ('旧タグ（廃止）')
    expect (link).toBeInTheDocument ()
    expect (marker.closest ('a')).toBeNull ()
  })
})
