import '@testing-library/jest-dom/vitest';
import { render, waitFor } from '@testing-library/vue';
import userEvent from '@testing-library/user-event';
import { describe, expect, test } from 'vitest';
import {
  UiSelect,
  UiSelectTrigger,
  UiSelectContent,
  UiSelectItem,
  UiSelectValue,
} from '../index';

describe('UiSelectContent', () => {
  test('applies custom class', async () => {
    const user = userEvent.setup();
    const { getByRole } = render({
      components: {
        UiSelect,
        UiSelectTrigger,
        UiSelectContent,
        UiSelectItem,
        UiSelectValue,
      },
      template: `
        <UiSelect>
          <UiSelectTrigger>
            <UiSelectValue placeholder="Select" />
          </UiSelectTrigger>
          <UiSelectContent class="max-h-[200px]">
            <UiSelectItem value="a">Option A</UiSelectItem>
          </UiSelectContent>
        </UiSelect>
      `,
    });

    await user.click(getByRole('combobox'));

    await waitFor(() => {
      expect(getByRole('listbox')).toHaveClass('max-h-[200px]');
    });
  });

  test('does not mount multi-select content while closed or lose selected label', async () => {
    const { container, getByRole } = render({
      components: {
        UiSelect,
        UiSelectTrigger,
        UiSelectContent,
        UiSelectItem,
        UiSelectValue,
      },
      template: `
        <UiSelect :multiple="true" :default-value="['a']">
          <UiSelectTrigger>
            <UiSelectValue placeholder="Select" />
          </UiSelectTrigger>
          <UiSelectContent>
            <UiSelectItem value="a">Option A</UiSelectItem>
          </UiSelectContent>
        </UiSelect>
      `,
    });

    await waitFor(() => {
      expect(getByRole('combobox')).toHaveTextContent('Option A');
    });
    expect(
      container.ownerDocument.body.querySelector(
        '[data-slot="select-content"]',
      ),
    ).not.toBeInTheDocument();
  });

  test('ports multi-select content through the select portal', async () => {
    const user = userEvent.setup();
    const { container, getByRole } = render({
      components: {
        UiSelect,
        UiSelectTrigger,
        UiSelectContent,
        UiSelectItem,
        UiSelectValue,
      },
      template: `
        <UiSelect :multiple="true">
          <UiSelectTrigger>
            <UiSelectValue placeholder="Select" />
          </UiSelectTrigger>
          <UiSelectContent class="max-h-[200px]">
            <UiSelectItem value="a">Option A</UiSelectItem>
          </UiSelectContent>
        </UiSelect>
      `,
    });

    await user.click(getByRole('combobox'));

    await waitFor(() => {
      const content = container.ownerDocument.body.querySelector(
        '[data-slot="select-content"]',
      );
      expect(content).toHaveClass('max-h-[200px]');
      expect(container).not.toContainElement(content as HTMLElement);
    });
  });
});
