import { ComponentFixture, TestBed } from '@angular/core/testing';
import { <%= classify(name) %> } from './<%= dasherize(name) %>';

describe('<%= classify(name) %>', () => {
  let fixture: ComponentFixture<<%= classify(name) %>>;

  beforeEach(async () => {
    await TestBed.configureTestingModule({
      imports: [<%= classify(name) %>],
    }).compileComponents();

    fixture = TestBed.createComponent(<%= classify(name) %>);
    fixture.detectChanges();
  });

  function openButton(): HTMLButtonElement {
    return fixture.nativeElement.querySelector('button');
  }

  function dialog(): HTMLElement | null {
    return fixture.nativeElement.querySelector('[role="dialog"]');
  }

  it('starts closed with an opening trigger', () => {
    expect(openButton().textContent?.trim()).toBe('Open dialog');
    expect(dialog()).toBeNull();
  });

  it('opens a modal dialog with labelled title', () => {
    openButton().click();
    fixture.detectChanges();

    const element = dialog();
    const title = fixture.nativeElement.querySelector('h2');

    expect(element).toBeTruthy();
    expect(element?.getAttribute('aria-modal')).toBe('true');
    expect(element?.getAttribute('aria-labelledby')).toBe(title.id);
    expect(element?.getAttribute('tabindex')).toBe('-1');
    expect(title.textContent?.trim()).toBe('Dialog title');
  });

  it('closes with the close button and restores focus to the trigger', () => {
    const trigger = openButton();
    trigger.focus();
    trigger.click();
    fixture.detectChanges();

    const closeButton = Array.from(fixture.nativeElement.querySelectorAll('button')).at(-1) as HTMLButtonElement;
    closeButton.click();
    fixture.detectChanges();

    expect(dialog()).toBeNull();
    expect(document.activeElement).toBe(trigger);
  });

  it('closes with Escape from inside the dialog', () => {
    const trigger = openButton();
    trigger.click();
    fixture.detectChanges();

    dialog()?.dispatchEvent(new KeyboardEvent('keydown', { key: 'Escape', bubbles: true }));
    fixture.detectChanges();

    expect(dialog()).toBeNull();
    expect(document.activeElement).toBe(trigger);
  });
});
