import { Component } from '@angular/core';
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { By } from '@angular/platform-browser';

import { <%= classify(name) %> } from './<%= dasherize(name) %>';

@Component({
  imports: [<%= classify(name) %>],
  template: `<<%= selector %> />`,
})
class HostComponent {}

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

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

    fixture = TestBed.createComponent(HostComponent);
    fixture.detectChanges();
    host = fixture.nativeElement as HTMLElement;
  });

  it('renders spinbutton semantics and value bounds', () => {
    const input = host.querySelector<HTMLInputElement>('[role="spinbutton"]');

    expect(input).toBeTruthy();
    expect(input?.getAttribute('aria-labelledby')).toBeTruthy();
    expect(input?.getAttribute('aria-valuemin')).toBe('0');
    expect(input?.getAttribute('aria-valuemax')).toBe('99');
    expect(input?.getAttribute('aria-valuenow')).toBe('1');
  });

  it('increments and decrements from buttons and keyboard', () => {
    const inputDebug = fixture.debugElement.query(By.css('[role="spinbutton"]'));
    const input = inputDebug.nativeElement as HTMLInputElement;
    const buttons = Array.from(host.querySelectorAll<HTMLButtonElement>('button'));

    buttons[1].click();
    fixture.detectChanges();
    expect(input.value).toBe('2');
    expect(input.getAttribute('aria-valuenow')).toBe('2');

    inputDebug.triggerEventHandler('keydown', new KeyboardEvent('keydown', { key: 'ArrowDown' }));
    fixture.detectChanges();
    expect(input.value).toBe('1');

    buttons[0].click();
    fixture.detectChanges();
    expect(input.value).toBe('0');

    inputDebug.triggerEventHandler('keydown', new KeyboardEvent('keydown', { key: 'ArrowDown' }));
    fixture.detectChanges();
    expect(input.value).toBe('0');
  });

  it('accepts typed numbers and clamps them to the supported range', () => {
    const inputDebug = fixture.debugElement.query(By.css('[role="spinbutton"]'));
    const input = inputDebug.nativeElement as HTMLInputElement;

    input.value = '120';
    inputDebug.triggerEventHandler('change', { target: input });
    fixture.detectChanges();
    expect(input.value).toBe('99');

    input.value = '-10';
    inputDebug.triggerEventHandler('change', { target: input });
    fixture.detectChanges();
    expect(input.value).toBe('0');
  });
});
