import { describe, it, expect, beforeEach } from 'vitest';
import { typeahead } from './typeahead.js';
import { mountHost, connectTrait, spyEvent, resetDOM, wait } from '../test-helpers.js';

function child(host, text) {
  const li = document.createElement('div');
  li.textContent = text;
  li.setAttribute('role', 'option');
  host.appendChild(li);
  return li;
}

describe('typeahead', () => {
  beforeEach(resetDOM);

  it('typing first letter matches a child by textContent', async () => {
    const host = mountHost();
    child(host, 'Apple');
    child(host, 'Banana');
    child(host, 'Cherry');
    connectTrait(typeahead, host);
    const spy = spyEvent(host, 'typeahead-match');
    host.dispatchEvent(new KeyboardEvent('keydown', { key: 'b' }));
    await wait(20);
    expect(spy.count).toBeGreaterThanOrEqual(1);
    expect(spy.last.element?.textContent).toBe('Banana');
  });

  it('disconnect removes the keydown listener', () => {
    const host = mountHost();
    child(host, 'Apple');
    const inst = connectTrait(typeahead, host);
    const spy = spyEvent(host, 'typeahead-match');
    inst.disconnect(host);
    host.dispatchEvent(new KeyboardEvent('keydown', { key: 'a' }));
    expect(spy.count).toBe(0);
  });
});
