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

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

  it('fires "hotkey" event on matching combo', () => {
    const host = mountHost('div', { 'data-hotkey': 'ctrl+k' });
    connectTrait(hotkey, host);
    const spy = spyEvent(host, 'hotkey');
    host.dispatchEvent(new KeyboardEvent('keydown', { key: 'k', ctrlKey: true }));
    expect(spy.count).toBe(1);
    expect(spy.last.combo).toBe('ctrl+k');
  });

  it('does not fire on non-matching combo', () => {
    const host = mountHost('div', { 'data-hotkey': 'ctrl+k' });
    connectTrait(hotkey, host);
    const spy = spyEvent(host, 'hotkey');
    host.dispatchEvent(new KeyboardEvent('keydown', { key: 'j', ctrlKey: true }));
    host.dispatchEvent(new KeyboardEvent('keydown', { key: 'k' }));
    host.dispatchEvent(new KeyboardEvent('keydown', { key: 'k', altKey: true }));
    expect(spy.count).toBe(0);
  });

  it('shift modifier required when declared', () => {
    const host = mountHost('div', { 'data-hotkey': 'shift+a' });
    connectTrait(hotkey, host);
    const spy = spyEvent(host, 'hotkey');
    host.dispatchEvent(new KeyboardEvent('keydown', { key: 'a' }));
    expect(spy.count).toBe(0);
    host.dispatchEvent(new KeyboardEvent('keydown', { key: 'a', shiftKey: true }));
    expect(spy.count).toBe(1);
  });

  it('global mode listens on document', () => {
    const host = mountHost('div', { 'data-hotkey': 'ctrl+/', 'data-hotkey-global': '' });
    connectTrait(hotkey, host);
    const spy = spyEvent(host, 'hotkey');
    document.dispatchEvent(new KeyboardEvent('keydown', { key: '/', ctrlKey: true }));
    expect(spy.count).toBe(1);
  });

  it('non-global mode does not listen on document', () => {
    const host = mountHost('div', { 'data-hotkey': 'ctrl+/' });
    connectTrait(hotkey, host);
    const spy = spyEvent(host, 'hotkey');
    document.dispatchEvent(new KeyboardEvent('keydown', { key: '/', ctrlKey: true }));
    expect(spy.count).toBe(0);
  });

  it('disconnect removes the keydown listener', () => {
    const host = mountHost('div', { 'data-hotkey': 'ctrl+k', 'data-hotkey-global': '' });
    const inst = connectTrait(hotkey, host);
    const spy = spyEvent(host, 'hotkey');
    inst.disconnect(host);
    document.dispatchEvent(new KeyboardEvent('keydown', { key: 'k', ctrlKey: true }));
    expect(spy.count).toBe(0);
  });
});
