import { TestBed } from '@angular/core/testing';
import { beforeEach, describe, expect, it } from 'vitest';

import { QuantitySelectorComponent } from './quantity-selector.component';

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

  it('stops increasing when it reaches a numeric maximum', () => {
    const fixture = TestBed.createComponent(QuantitySelectorComponent);
    fixture.componentRef.setInput('max', 2);
    fixture.detectChanges();

    const increaseButton = fixture.nativeElement.querySelector(
      'button:last-child',
    ) as HTMLButtonElement;
    increaseButton.click();
    fixture.detectChanges();

    expect(fixture.componentInstance.quantity()).toBe(2);
    expect(increaseButton.disabled).toBe(true);
  });

  it('keeps increasing when maximum is null', () => {
    const fixture = TestBed.createComponent(QuantitySelectorComponent);
    fixture.componentRef.setInput('max', null);
    fixture.detectChanges();

    const increaseButton = fixture.nativeElement.querySelector(
      'button:last-child',
    ) as HTMLButtonElement;
    increaseButton.click();
    increaseButton.click();
    fixture.detectChanges();

    expect(fixture.componentInstance.quantity()).toBe(3);
    expect(increaseButton.disabled).toBe(false);
  });

  it('does not decrease below the configured minimum', () => {
    const fixture = TestBed.createComponent(QuantitySelectorComponent);
    fixture.detectChanges();

    const decreaseButton = fixture.nativeElement.querySelector(
      'button:first-child',
    ) as HTMLButtonElement;

    expect(decreaseButton.disabled).toBe(true);
    expect(fixture.componentInstance.quantity()).toBe(1);
  });

  it('disables both controls and ignores quantity changes when disabled', () => {
    const fixture = TestBed.createComponent(QuantitySelectorComponent);
    fixture.componentRef.setInput('quantity', 2);
    fixture.componentRef.setInput('disabled', true);
    fixture.detectChanges();

    const buttons = fixture.nativeElement.querySelectorAll('button') as NodeListOf<HTMLButtonElement>;

    expect(Array.from(buttons).every((button) => button.disabled)).toBe(true);
    expect(fixture.nativeElement.querySelector('[aria-disabled="true"]')).not.toBeNull();

    (fixture.componentInstance as any).onIncrease();
    (fixture.componentInstance as any).onDecrease();

    expect(fixture.componentInstance.quantity()).toBe(2);
  });
});
