import { afterEach, expect, test } from 'vitest'
import { page, userEvent } from 'vitest/browser'
import { createElement, useState } from 'react'
import { createRoot } from 'react-dom/client'
import { flushSync } from 'react-dom'
let root
afterEach(() => { if (root) { flushSync(() => root.unmount()); root = undefined } document.body.replaceChildren() })
function select(name = 'choices', multiple = false, duplicate = false) {
  const element = document.createElement('select')
  element.setAttribute('aria-label', name)
  element.multiple = multiple
  for (const [label, value] of [['Alpha', 'one'], ['Beta', duplicate ? 'one' : 'two'], ['Gamma', 'three']]) {
    const option = document.createElement('option'); option.textContent = label; option.value = value; element.append(option)
  }
  document.body.append(element)
  return element
}
function trace(element) {
  const events = []
  for (const type of ['input', 'change']) element.addEventListener(type, event => events.push({ type, target: event.target === element, currentTarget: event.currentTarget === element, trusted: event.isTrusted, bubbles: event.bubbles, composed: event.composed, values: [...element.selectedOptions].map(option => option.value), labels: [...element.selectedOptions].map(option => option.textContent), selectedIndex: element.selectedIndex }))
  return events
}
function row(name, element, events, extra = {}) { console.log('SELECT_OPTIONS_RAW ' + JSON.stringify({ name, events, value: element.value, selectedIndex: element.selectedIndex, selected: [...element.options].map(option => ({ label: option.textContent, value: option.value, selected: option.selected, connected: option.isConnected })), ...extra })) }
test('userEvent selects the actual option identity when values are duplicated', async () => {
  const element = select('choices', false, true), options = [...element.options], events = trace(element)
  const returned = await userEvent.selectOptions(element, options[1])
  expect(element.selectedIndex).toBe(1)
  expect(element.selectedOptions[0]).toBe(options[1])
  row('duplicate HTMLElement', element, events, { originalNodes: [...element.options].every((option, index) => option === options[index]), returnedUndefined: returned === undefined })
})
test('Locator selects an actual option Locator with the same duplicate value', async () => {
  const element = select('choices', false, true), events = trace(element)
  const returned = await page.getByLabelText('choices').selectOptions(page.getByRole('option', { name: 'Beta', exact: true }))
  expect(element.selectedIndex).toBe(1)
  row('duplicate Locator', element, events, { returnedUndefined: returned === undefined })
})
test('HTMLElement arrays preserve native selected option order and event identity', async () => {
  const element = select('choices', true), options = [...element.options], events = trace(element)
  const returned = await userEvent.selectOptions(page.getByLabelText('choices'), [options[2], options[0]])
  expect([...element.selectedOptions]).toEqual([options[0], options[2]])
  row('multiple HTMLElements', element, events, { originalNodes: [...element.options].every((option, index) => option === options[index]), returnedUndefined: returned === undefined })
})
test('setup-owned selectOptions accepts an array of live option Locators', async () => {
  const element = select('choices', true), events = trace(element), user = userEvent.setup()
  const returned = await user.selectOptions(element, [page.getByRole('option', { name: 'Gamma', exact: true }), page.getByRole('option', { name: 'Beta', exact: true })])
  expect([...element.selectedOptions].map(option => option.value)).toEqual(['two', 'three'])
  row('setup Locator array', element, events, { returnedUndefined: returned === undefined })
})
test('empty arrays retain the existing native clearing contract', async () => {
  const element = select('choices', true), events = trace(element)
  await userEvent.selectOptions(element, ['one', 'three'])
  const returned = await page.getByLabelText('choices').selectOptions([])
  expect(element.selectedOptions.length).toBe(0)
  row('empty selection', element, events, { returnedUndefined: returned === undefined })
})
test('option element selection awaits the controlled React render turn', async () => {
  function Controlled() {
    const [values, setValues] = useState(['one'])
    return createElement('section', null, createElement('select', { multiple: true, 'aria-label': 'controlled', value: values, onChange: event => setValues([...event.currentTarget.selectedOptions].map(option => option.value)) }, ...[['Alpha', 'one'], ['Beta', 'two'], ['Gamma', 'three']].map(([label, value]) => createElement('option', { key: value, value }, label))), createElement('output', { 'data-testid': 'selection' }, values.join(',')))
  }
  const container = document.createElement('div'); document.body.append(container); root = createRoot(container); flushSync(() => root.render(createElement(Controlled)))
  const element = page.getByLabelText('controlled').element(), events = trace(element), options = [...element.options]
  await userEvent.selectOptions(element, [options[1], options[2]])
  expect(page.getByTestId('selection').element().textContent).toBe('two,three')
  row('controlled component', element, events, { output: page.getByTestId('selection').element().textContent, originalNodes: [...element.options].every((option, index) => option === options[index]) })
})
test('native foreign-option rejection retains the following action and file realm', async () => {
  const element = select(), foreign = select('foreign'), events = trace(element)
  let rejected
  try { await userEvent.selectOptions(element, foreign.options[1], { timeout: 50 }) } catch (error) { rejected = error.name }
  expect(rejected).toBeDefined()
  await userEvent.selectOptions(element, 'three')
  expect(element.value).toBe('three')
  row('native rejection recovery', element, events, { rejectedName: rejected, foreignConnected: foreign.isConnected, foreignSelection: foreign.value })
})
