import { test, expect } from '@playwright/test'

test.describe('i18n language switching', () => {
  test('switches language and persists via cookie and reload', async ({ page, context }) => {
    await page.goto('/')
    await page.waitForLoadState('networkidle')

    // Open language switcher and choose English (button label is current locale, e.g., EN or NL)
    const switcherBtn = page.getByRole('button', { name: /^(EN|NL)$/ })
    await switcherBtn.first().click()
    const english = page.getByRole('menuitem').filter({ hasText: /english/i }).first()
    if (await english.count()) {
      await english.click()
      await expect(page).toHaveURL(/\/en(\/|$)/)
    }

    // Cookie is set
    const cookies = await context.cookies()
    const redirected = cookies.find(c => c.name === 'i18n_redirected')
    expect(redirected?.value).toMatch(/en|nl/)

    // Reload persists
    await page.reload()
    await expect(page).toHaveURL(/\/(en|nl)(\/|$)/)

    // Switch back to Nederlands (default locale is not prefixed)
    await switcherBtn.first().click()
    const dutch = page.getByRole('menuitem').filter({ hasText: /nederlands|dutch/i }).first()
    if (await dutch.count()) {
      await dutch.click()
      await expect(page).not.toHaveURL(/\/en(\/|$)/)

      // Cookie may be 'nl' or unset depending on module config
      const cookies2 = await context.cookies()
      const redirected2 = cookies2.find(c => c.name === 'i18n_redirected')
      if (redirected2) {
        expect(redirected2.value).toBe('nl')
      }
    }
  })
})
