import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react'
import { afterEach, describe, expect, it } from 'vitest'
import { LanguageProvider, LanguageSelector } from './i18n'

afterEach(() => {
  cleanup()
  localStorage.clear()
})

describe('runtime language selection', () => {
  it('switches UI text to Russian and persists the choice', async () => {
    localStorage.setItem('mixmaker-language', 'en')
    render(<LanguageProvider><LanguageSelector /><p>Your events</p></LanguageProvider>)
    fireEvent.change(screen.getByRole('combobox'), { target: { value: 'ru' } })
    await waitFor(() => expect(screen.getByText('Ваши события')).toBeInTheDocument())
    expect(localStorage.getItem('mixmaker-language')).toBe('ru')
    expect(document.documentElement.lang).toBe('ru')
  })

  it('restores English after switching back', async () => {
    localStorage.setItem('mixmaker-language', 'ru')
    render(<LanguageProvider><LanguageSelector /><p>Your events</p></LanguageProvider>)
    await waitFor(() => expect(screen.getByText('Ваши события')).toBeInTheDocument())
    fireEvent.change(screen.getByRole('combobox'), { target: { value: 'en' } })
    await waitFor(() => expect(screen.getByText('Your events')).toBeInTheDocument())
  })
})
