import { describe, it, expect, vi, beforeEach } from 'vitest'
import { render, screen, waitFor } from '@testing-library/react'
import { MemoryRouter, Route, Routes } from 'react-router-dom'
import VerifyEmail from '../pages/VerifyEmail'

vi.mock('../api/client', () => ({
  default: {
    post: vi.fn(),
    get: vi.fn(),
    interceptors: {
      request: { use: vi.fn() },
      response: { use: vi.fn() },
    },
  },
}))

import api from '../api/client'

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

  const renderPage = (search = '') =>
    render(
      <MemoryRouter initialEntries={[`/verify-email${search}`]}>
        <Routes>
          <Route path="/verify-email" element={<VerifyEmail />} />
        </Routes>
      </MemoryRouter>
    )

  it('shows loading state initially (with token)', () => {
    api.post.mockImplementation(() => new Promise(() => {}))
    renderPage('?token=abc123')
    expect(screen.getByText('Проверяем...')).toBeInTheDocument()
  })

  it('shows error when no token', async () => {
    renderPage()
    await waitFor(() => {
      expect(screen.getByText('Ошибка')).toBeInTheDocument()
      expect(screen.getByText('Токен не найден')).toBeInTheDocument()
    })
  })

  it('shows success state on successful verification', async () => {
    api.post.mockResolvedValueOnce({})
    renderPage('?token=valid-token')

    await waitFor(() => {
      expect(screen.getByText('Готово! 🎉')).toBeInTheDocument()
      expect(screen.getByText('Email успешно подтверждён!')).toBeInTheDocument()
    })
  })

  it('shows login link on success', async () => {
    api.post.mockResolvedValueOnce({})
    renderPage('?token=valid-token')

    await waitFor(() => {
      expect(screen.getByText('Войти в аккаунт')).toBeInTheDocument()
    })
  })

  it('shows error state on failed verification', async () => {
    api.post.mockRejectedValueOnce({ response: { data: { error: 'Token expired' } } })
    renderPage('?token=expired-token')

    await waitFor(() => {
      expect(screen.getByText('Ошибка')).toBeInTheDocument()
      expect(screen.getByText('Token expired')).toBeInTheDocument()
    })
  })

  it('calls verify endpoint with token', async () => {
    api.post.mockResolvedValueOnce({})
    renderPage('?token=mytoken')

    await waitFor(() => {
      expect(api.post).toHaveBeenCalledWith('/auth/verify-email', { token: 'mytoken' })
    })
  })
})
