import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import { render, screen, fireEvent } from '@testing-library/react'
import { MemoryRouter } from 'react-router-dom'
import { describe, expect, it, vi } from 'vitest'
import { AuthPage } from '../ui/AuthPage'

vi.mock('@/shared/api/client', () => ({ apiClient: { post: vi.fn() } }))
vi.mock('effector-react', async () => {
  const actual = await vi.importActual('effector-react')
  return { ...actual, useUnit: () => null }
})

function renderPage() {
  const qc = new QueryClient({ defaultOptions: { queries: { retry: false } } })
  return render(
    <QueryClientProvider client={qc}>
      <MemoryRouter>
        <AuthPage />
      </MemoryRouter>
    </QueryClientProvider>,
  )
}

describe('AuthPage', () => {
  it('renders two tabs', () => {
    renderPage()
    expect(screen.getByRole('button', { name: 'Пароль' })).toBeTruthy()
    expect(screen.getByRole('button', { name: 'Код' })).toBeTruthy()
  })

  it('shows OAuth buttons and separator always', () => {
    renderPage()
    expect(screen.getByText('или')).toBeTruthy()
    expect(screen.getByText('Войти через VK ID')).toBeTruthy()
    expect(screen.getByText('Войти через Яндекс ID')).toBeTruthy()
  })

  it('shows login form by default on tab 0', () => {
    renderPage()
    expect(screen.getByText('Вход')).toBeTruthy()
    expect(screen.getByText('Регистрация')).toBeTruthy()
    const buttons = screen.getAllByRole('button')
    const loginBtn = buttons.find((b) => b.textContent === 'Войти')
    expect(loginBtn).toBeTruthy()
  })

  it('switches to code tab', () => {
    renderPage()
    fireEvent.click(screen.getByText('Код'))
    expect(screen.getByText('Отправить код')).toBeTruthy()
  })

  it('shows auth password form with login by default', () => {
    renderPage()
    expect(screen.getByText('Вход')).toBeTruthy()
    expect(screen.getByText('Регистрация')).toBeTruthy()
  })

  it('switches to code tab', () => {
    renderPage()
    fireEvent.click(screen.getByText('Код'))
    expect(screen.getByText('Отправить код')).toBeTruthy()
  })
})
