import { afterEach, beforeEach, expect, test } from 'vitest';
import { act } from 'react';
import { createRoot, type Root } from 'react-dom/client';
import { SelectControl } from './SelectControl';

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

let container: HTMLDivElement;
let root: Root;

beforeEach(() => {
  container = document.createElement('div');
  document.body.appendChild(container);
  root = createRoot(container);
});

afterEach(() => {
  act(() => root.unmount());
  container.remove();
});

test('opens to the option list; a dividerBefore option draws a separator above itself', async () => {
  await act(async () => {
    root.render(
      <SelectControl
        id="sc-test"
        label="Pick"
        options={[
          { value: 'a', label: 'A' },
          { value: 'b', label: 'B', dividerBefore: true },
        ]}
        value="a"
        onSelect={() => {}}
      />,
    );
    await Promise.resolve();
  });

  const trigger = container.querySelector('button')!;
  await act(async () => {
    trigger.click();
    await Promise.resolve();
  });

  // The panel is portaled to <body>; both options render, with one presentation
  // divider sitting between A and B (visual only — not in the keyboard order).
  const panel = document.getElementById('sc-test')!;
  const labels = Array.from(panel.querySelectorAll('button')).map((b) => b.textContent);
  expect(labels.some((t) => t?.includes('A'))).toBe(true);
  expect(labels.some((t) => t?.includes('B'))).toBe(true);
  const dividers = panel.querySelectorAll('[role="presentation"]');
  expect(dividers).toHaveLength(1);
  expect(dividers[0].nextElementSibling?.textContent).toContain('B');
});
