import { getTestBed, TestBed } from '@angular/core/testing';
import { BrowserTestingModule, platformBrowserTesting } from '@angular/platform-browser/testing';
import { beforeAll, describe, expect, it } from 'vitest';

import { CheckoutPaymentTransferComponent } from './checkout-payment-transfer.component';

describe('CheckoutPaymentTransferComponent', () => {
  beforeAll(() => {
    try {
      getTestBed().initTestEnvironment(BrowserTestingModule, platformBrowserTesting());
    } catch {
      // Test environment may already be initialized by another setup entrypoint.
    }
  });

  it('renders the payment verification overlay while checking the transfer', async () => {
    await TestBed.configureTestingModule({
      imports: [CheckoutPaymentTransferComponent],
    }).compileComponents();

    const fixture = TestBed.createComponent(CheckoutPaymentTransferComponent);
    fixture.componentRef.setInput('validationStatus', 'checking');
    fixture.detectChanges();

    const overlay = fixture.nativeElement.querySelector('.payment-verification') as HTMLElement;
    expect(overlay).not.toBeNull();
    expect(overlay.textContent).toContain('Verificando pago');
    expect(overlay.querySelector('.payment-verification__spinner')).not.toBeNull();
  });

  it('shows the QR payment error and WhatsApp action when validation fails', async () => {
    await TestBed.configureTestingModule({
      imports: [CheckoutPaymentTransferComponent],
    }).compileComponents();

    const fixture = TestBed.createComponent(CheckoutPaymentTransferComponent);
    fixture.componentRef.setInput('validationStatus', 'error');
    fixture.componentRef.setInput('paymentAmount', 300000);
    fixture.componentRef.setInput('whatsappUrl', 'https://wa.me/543412602222');
    fixture.detectChanges();

    const element = fixture.nativeElement as HTMLElement;
    const whatsapp = Array.from(element.querySelectorAll('button')).find((button) =>
      button.textContent?.includes('WhatsApp'),
    );
    expect(element.textContent).toMatch(/No pudimos verificar el pago de \$\s*300\.000\./);
    expect(whatsapp).toBeDefined();
    expect(element.querySelector('.payment-verification')).toBeNull();
  });

  it('shows a custom validation title for a near DNI candidate', async () => {
    await TestBed.configureTestingModule({
      imports: [CheckoutPaymentTransferComponent],
    }).compileComponents();

    const fixture = TestBed.createComponent(CheckoutPaymentTransferComponent);
    fixture.componentRef.setInput('validationStatus', 'error');
    fixture.componentRef.setInput(
      'verificationErrorTitle',
      'El DNI no corresponde con el de la transferencia',
    );
    fixture.detectChanges();

    expect(fixture.nativeElement.textContent).toContain(
      'El DNI no corresponde con el de la transferencia',
    );
    expect(fixture.nativeElement.textContent).not.toContain('No pudimos verificar el pago de');
  });
});
