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

import {
  ConfirmModalData,
  MODAL_DATA,
  ModalRef
} from '../../../core/services/modal.service';
import { ConfirmModalComponent } from './confirm-modal.component';

describe('ConfirmModalComponent', () => {
  const data: ConfirmModalData = {
    content: 'Se confirmara la operacion seleccionada.',
    confirmLabel: 'Aceptar',
    cancelLabel: 'Volver'
  };

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

  afterEach(() => {
    TestBed.resetTestingModule();
  });

  it('renders the configured content and labels', async () => {
    await TestBed.configureTestingModule({
      imports: [ConfirmModalComponent],
      providers: [
        {
          provide: MODAL_DATA,
          useValue: data
        },
        {
          provide: ModalRef,
          useValue: {
            close: vi.fn()
          }
        }
      ]
    }).compileComponents();

    const fixture = TestBed.createComponent(ConfirmModalComponent);
    fixture.detectChanges();

    const element = fixture.nativeElement as HTMLElement;

    expect(element.textContent).toContain(data.content);
    expect(element.textContent).toContain(data.confirmLabel);
    expect(element.textContent).toContain(data.cancelLabel);
  });

  it('closes with false on cancel and true on confirm', async () => {
    const closeSpy = vi.fn();

    await TestBed.configureTestingModule({
      imports: [ConfirmModalComponent],
      providers: [
        {
          provide: MODAL_DATA,
          useValue: data
        },
        {
          provide: ModalRef,
          useValue: {
            close: closeSpy
          }
        }
      ]
    }).compileComponents();

    const fixture = TestBed.createComponent(ConfirmModalComponent);
    fixture.detectChanges();

    const buttons = fixture.nativeElement.querySelectorAll('button');

    buttons[0].click();
    buttons[1].click();

    expect(closeSpy).toHaveBeenNthCalledWith(1, false);
    expect(closeSpy).toHaveBeenNthCalledWith(2, true);
  });
});
