// @vitest-environment jsdom
//
// The auth form. We assert config + that it renders email/password fields and
// toggles between sign-in and sign-up. The network submit (CSRF + POST /auth/*)
// is exercised against a running api by `voltro dev`, not unit-mocked here.

import { afterEach, describe, expect, test } from 'vitest'
import { act, createElement, type ReactNode } from 'react'
import { createRoot, type Root } from 'react-dom/client'
import { I18nProvider } from '@voltro/i18n'
import enCatalog from '../../locales/en'

const { default: Login, meta, renderMode } = await import('./page')

;(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true

let container: HTMLDivElement
let root: Root

const render = (node: ReactNode): void => {
  container = document.createElement('div')
  document.body.appendChild(container)
  act(() => {
    root = createRoot(container)
    root.render(
      createElement(I18nProvider, { locale: 'en', messages: enCatalog, defaultLocale: 'en', children: node }),
    )
  })
}

afterEach(() => {
  if (root) act(() => root.unmount())
  container?.remove()
  document.body.innerHTML = ''
})

describe('login — config', () => {
  test('is a static page titled Sign in', () => {
    expect(renderMode).toBe('static')
    expect(meta({ locale: 'en' }).title).toBe('Sign in')
  })
})

describe('login — form', () => {
  test('renders email + password inputs and defaults to sign-in', () => {
    render(createElement(Login))
    expect(container.querySelector('input[type="email"]')).not.toBeNull()
    expect(container.querySelector('input[type="password"]')).not.toBeNull()
    expect(container.querySelector('h1')?.textContent).toBe('Sign in')
  })

  test('toggling switches to the create-account heading', () => {
    render(createElement(Login))
    const toggle = container.querySelector('.link')!
    act(() => { toggle.dispatchEvent(new MouseEvent('click', { bubbles: true })) })
    expect(container.querySelector('h1')?.textContent).toBe('Create your account')
  })
})
