import { fireEvent, screen, waitFor } from '@testing-library/react'
import { describe, expect, it, vi } from 'vitest'

import WikiSearchPage from '@/pages/wiki/WikiSearchPage'
import { buildWikiPage } from '@/test/factories'
import { renderWithProviders } from '@/test/render'

const api = vi.hoisted (() => ({
  apiGet: vi.fn (),
}))

vi.mock ('@/lib/api', () => api)

describe ('WikiSearchPage', () => {
  it ('loads initial wiki pages and renders links', async () => {
    api.apiGet.mockResolvedValueOnce ([buildWikiPage ({ title: '虹夏' })])

    renderWithProviders (<WikiSearchPage/>)

    expect (await screen.findByRole ('link', { name: '虹夏' })).toHaveAttribute (
        'href',
        '/wiki/%E8%99%B9%E5%A4%8F',
    )
    expect (api.apiGet).toHaveBeenCalledWith ('/wiki', { params: { title: '' } })
  })

  it ('searches by title on submit', async () => {
    api.apiGet
      .mockResolvedValueOnce ([])
      .mockResolvedValueOnce ([buildWikiPage ({ title: '検索結果' })])

    renderWithProviders (<WikiSearchPage/>)

    fireEvent.change (screen.getAllByRole ('textbox')[0], { target: { value: '検索' } })
    fireEvent.click (screen.getByRole ('button', { name: '検索' }))

    await waitFor (() => {
      expect (api.apiGet).toHaveBeenLastCalledWith (
          '/wiki',
          { params: { title: '検索' } },
      )
    })
    expect (await screen.findByRole ('link', { name: '検索結果' })).toBeInTheDocument ()
  })

  it ('marks deprecated wiki tags in the result title', async () => {
    api.apiGet.mockResolvedValueOnce ([
        buildWikiPage ({
            title:        '旧タグ',
            deprecatedAt: '2026-06-01T00:00:00.000Z',
        }),
    ])

    renderWithProviders (<WikiSearchPage/>)

    const link = await screen.findByRole ('link', { name: '旧タグ' })
    const marker = screen.getByText ('（廃止）')

    expect (link).toBeInTheDocument ()
    expect (marker.closest ('a')).toBeNull ()
  })
})
