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

import { CheckoutPaymentQrComponent } from './checkout-payment-qr.component';

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

  it('renders the animated payment verification overlay over the QR', async () => {
    await TestBed.configureTestingModule({
      imports: [CheckoutPaymentQrComponent],
    }).compileComponents();

    const fixture = TestBed.createComponent(CheckoutPaymentQrComponent);
    fixture.componentRef.setInput('isCheckingPayment', true);
    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 payment verification error and WhatsApp action after timeout', async () => {
    await TestBed.configureTestingModule({
      imports: [CheckoutPaymentQrComponent],
    }).compileComponents();

    const fixture = TestBed.createComponent(CheckoutPaymentQrComponent);
    fixture.componentRef.setInput('paymentStatus', 'timed_out');
    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(element.textContent).toContain('Por favor contactate con nosotros para resolverlo.');
    expect(whatsapp).toBeDefined();
    expect(element.textContent).not.toContain('Volver a verificar');
  });
});
