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

function focusableChild(host, label) {
  const btn = document.createElement('button');
  btn.textContent = label;
  host.appendChild(btn);
  return btn;
}

describe('focus-trap', () => {
  beforeEach(resetDOM);

  it('connect sets data-focus-trap-active', () => {
    const host = mountHost();
    focusableChild(host, 'A');
    focusableChild(host, 'B');
    connectTrait(focusTrap, host);
    expect(host.hasAttribute('data-focus-trap-active')).toBe(true);
  });

  it('Escape fires focus-trap-escape event', () => {
    const host = mountHost();
    focusableChild(host, 'A');
    connectTrait(focusTrap, host);
    const spy = spyEvent(host, 'focus-trap-escape');
    host.dispatchEvent(new KeyboardEvent('keydown', { key: 'Escape', bubbles: true }));
    expect(spy.count).toBeGreaterThanOrEqual(1);
  });

  it('disconnect clears attribute and stops listening', () => {
    const host = mountHost();
    focusableChild(host, 'A');
    const inst = connectTrait(focusTrap, host);
    const spy = spyEvent(host, 'focus-trap-escape');
    inst.disconnect(host);
    expect(host.hasAttribute('data-focus-trap-active')).toBe(false);
    host.dispatchEvent(new KeyboardEvent('keydown', { key: 'Escape', bubbles: true }));
    expect(spy.count).toBe(0);
  });
});
