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

describe('keyboard-nav', () => {
  beforeEach(resetDOM);

  it.each([
    ['ArrowUp', 'nav-up'],
    ['ArrowDown', 'nav-down'],
    ['ArrowLeft', 'nav-left'],
    ['ArrowRight', 'nav-right'],
    ['Enter', 'nav-enter'],
    ['Escape', 'nav-escape'],
    ['Home', 'nav-home'],
    ['End', 'nav-end'],
  ])('%s keydown fires %s event', (key, eventName) => {
    const host = mountHost();
    connectTrait(keyboardNav, host);
    const spy = spyEvent(host, eventName);
    host.dispatchEvent(new KeyboardEvent('keydown', { key }));
    expect(spy.count).toBe(1);
  });

  it('unrelated key does not fire any nav event', () => {
    const host = mountHost();
    connectTrait(keyboardNav, host);
    const spy = spyEvent(host, 'nav-up');
    host.dispatchEvent(new KeyboardEvent('keydown', { key: 'a' }));
    expect(spy.count).toBe(0);
  });

  it('disconnect removes the keydown listener', () => {
    const host = mountHost();
    const inst = connectTrait(keyboardNav, host);
    const spy = spyEvent(host, 'nav-up');
    inst.disconnect(host);
    host.dispatchEvent(new KeyboardEvent('keydown', { key: 'ArrowUp' }));
    expect(spy.count).toBe(0);
  });
});
