// eslint-disable-next-line @typescript-eslint/triple-slash-reference
/// <reference path="../../../../test/src/custom_typings/chai.d.ts" />
/* eslint-disable no-undef */
import { ZuiButton } from '@zywave/zui-button';
import { ZuiIcon } from '@zywave/zui-icons';
import { assert } from '@esm-bundle/chai';
import { awaitEvent, constructHtml } from '../../../../test/src/util/helpers';
import { sendKeys } from '@web/test-runner-commands';

suite('zui-button', () => {
  let element: ZuiButton;

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

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

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

  test('ZuiButton, text slotted correctly', async () => {
    const text = 'boton';
    const slot = document.createElement('slot');
    slot.innerText = text;
    element.appendChild(slot);
    await element.updateComplete;
    assert.equal(slot.innerText, text);
  });

  test('ZuiButton, icon and text slotted correctly', async () => {
    const text = 'boton';
    const slotString = `
      <slot>
        ${text}
        <zui-icon icon="zui-check"></zui-icon>
      </slot>
    `;
    const slot = constructHtml(slotString);
    element.appendChild(slot);
    await element.updateComplete;
    const slotted = element.shadowRoot!.querySelector('slot').assignedNodes()[0].childNodes;
    const slottedText = slotted[0].textContent.trim();
    const slottedIcon = slotted[1];
    assert.equal(slottedText, text);
    assert.instanceOf(slottedIcon, ZuiIcon);
  });

  test('ZuiButton, icon only properly slotted', async () => {
    const slotString = `
      <slot><zui-icon icon="zui-check"></zui-icon></slot>
    `;
    const slot = constructHtml(slotString);
    element.appendChild(slot);
    element.setAttribute('icon', '');
    await element.updateComplete;
    const slottedIcon = element.shadowRoot!.querySelector('slot').assignedNodes()[0].childNodes[0];
    assert.instanceOf(slottedIcon, ZuiIcon);
  });

  test('hitting Enter while focusing button properly dispatches click events', async () => {
    await element.updateComplete;

    element.focus();

    const keys = sendKeys({
      press: 'Enter',
    });
    const clickEvent = awaitEvent(element, 'click', 1000);

    try {
      await Promise.all([keys, clickEvent]);
    } catch (err) {
      assert.isFalse(true, `Launch event didn't fire after 1000ms. Reason: ${err}`);
    }
  });
});
