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

@Component({
  imports: [<%= classify(name) %>],
  template: `
    <<%= selector %>
      title="Novo beneficiário"
      (beneficiarySubmit)="submitted = $event"
      (beneficiaryReset)="reset = true"
    />
  `,
})
class HostComponent {
  submitted: <%= classify(name) %>Value | null = null;
  reset = false;
}

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

  beforeEach(async () => {
    await TestBed.configureTestingModule({ imports: [HostComponent] }).compileComponents();
    fixture = TestBed.createComponent(HostComponent);
    fixture.detectChanges();
  });

  function control(name: string): HTMLInputElement | HTMLSelectElement {
    return fixture.nativeElement.querySelector(`[name="${name}"]`);
  }

  function submit(): void {
    fixture.nativeElement.querySelector('form').dispatchEvent(new SubmitEvent('submit', { bubbles: true, cancelable: true }));
    fixture.detectChanges();
  }

  it('renders a labelled native form for beneficiary data', () => {
    expect(fixture.nativeElement.querySelector('form').getAttribute('aria-labelledby')).toBe(
      fixture.nativeElement.querySelector('legend').id,
    );
    expect(control('document')).toBeTruthy();
    expect(control('bankCode')).toBeTruthy();
    expect(control('accountType')).toBeTruthy();
  });

  it('validates required fields before emitting', () => {
    submit();

    expect(fixture.nativeElement.querySelector('[role="alert"]').textContent).toContain('obrigatório');
    expect(fixture.componentInstance.submitted).toBeNull();
  });

  it('emits complete beneficiary details and reset', () => {
    const values = {
      name: 'Acme Corp',
      document: '12345678000199',
      bankCode: '001',
      branch: '1234',
      account: '98765',
    };

    for (const [name, value] of Object.entries(values)) {
      control(name).value = value;
      control(name).dispatchEvent(new Event('input', { bubbles: true }));
    }
    fixture.detectChanges();

    submit();

    expect(fixture.componentInstance.submitted?.name).toBe('Acme Corp');

    fixture.nativeElement.querySelector('button[type="button"]').click();
    fixture.detectChanges();

    expect(fixture.componentInstance.reset).toBe(true);
  });
});
