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 trigger(): HTMLButtonElement {
    return fixture.nativeElement.querySelector('button');
  }

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

  it('starts closed with a destructive-action trigger', () => {
    expect(trigger().textContent?.trim()).toBe('Delete item');
    expect(dialog()).toBeNull();
  });

  it('opens an alertdialog with modal, title, and description semantics', () => {
    trigger().click();
    fixture.detectChanges();

    const element = dialog();
    const title = fixture.nativeElement.querySelector('h2');
    const description = fixture.nativeElement.querySelector(`#${element?.getAttribute('aria-describedby')}`);

    expect(element).toBeTruthy();
    expect(element?.getAttribute('aria-modal')).toBe('true');
    expect(element?.getAttribute('aria-labelledby')).toBe(title.id);
    expect(description?.textContent).toContain('This action cannot be undone.');
  });

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

    const cancelButton = Array.from(fixture.nativeElement.querySelectorAll('button'))[1] as HTMLButtonElement;
    cancelButton.click();
    fixture.detectChanges();

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

  it('closes with Escape', () => {
    trigger().click();
    fixture.detectChanges();

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

    expect(dialog()).toBeNull();
  });
});
