// eslint-disable-next-line @typescript-eslint/triple-slash-reference
/// <reference path="../../../../test/src/custom_typings/chai.d.ts" />
/* eslint-disable no-undef */
import { ZuiSelectElement } from '@zywave/zui-select';
import { assert } from '@esm-bundle/chai';
import { randString } from '@zywave/../../test/src/util/helpers';
import { faceTests } from '../../../../test/src/util/face-tests';
import type { ZuiOptionElement } from '@zywave/zui-select';

suite('zui-select', () => {
  let element: ZuiSelectElement;

  setup(() => {
    element = document.createElement('zui-select') as ZuiSelectElement;
    document.body.appendChild(element);
  });

  teardown(() => {
    document.body.removeChild(element);
  });

  test('initializes as a ZuiSelectElement', () => {
    assert.instanceOf(element, ZuiSelectElement);
  });

  // TODO(pat) zui-select should be more aligned with native select, where options support a [selected] attribute
  test.skip('select respects option marked as selected', async () => {
    const options: ZuiOptionElement[] = [];
    for (let i = 0; i < 5; i++) {
      const option = document.createElement('zui-option') as ZuiOptionElement;
      option.value = randString();
      options.push(option);
      element.appendChild(option);
    }

    const randIndex = Math.floor(Math.random() * options.length);
    const randOption = options[randIndex];
    randOption.setAttribute('selected', '');

    await element.updateComplete;

    assert.equal(element.value, randOption.value);
  });

  test('select with value specified properly marks option as selected', async () => {
    const options: ZuiOptionElement[] = [];
    for (let i = 0; i < 5; i++) {
      const option = document.createElement('zui-option') as ZuiOptionElement;
      option.value = randString();
      options.push(option);
      element.appendChild(option);
    }

    const randIndex = Math.floor(Math.random() * options.length);
    const randOption = options[randIndex];
    element.setAttribute('value', randOption.value!);

    await element.updateComplete;

    assert.equal(element.value, randOption.value);

    const option = element.shadowRoot?.querySelector(`option[value='${randOption.value}'][selected]`);
    assert.exists(option);
  });
});

const initialValue = randString();
faceTests<ZuiSelectElement>('zui-select', {
  defaultValue: initialValue,
  valueAccessor(element) {
    return element.value;
  },
  preConfigure(element) {
    element.setAttribute('value', initialValue);
    const selectedOption = document.createElement('zui-option');
    selectedOption.setAttribute('value', initialValue);
    element.appendChild(selectedOption);

    const otherOption = document.createElement('zui-option');
    otherOption.setAttribute('value', randString());
    element.appendChild(otherOption);
  },
});
