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 { ConfirmDeleteModalComponent } from './confirm-delete-modal.component';

describe('ConfirmDeleteModalComponent', () => {
  const data: ConfirmModalData = {
    content: 'Se eliminara el elemento seleccionado.',
    confirmLabel: 'Eliminar',
    cancelLabel: 'Cancelar'
  };

  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 uses danger for the confirm action', async () => {
    await TestBed.configureTestingModule({
      imports: [ConfirmDeleteModalComponent],
      providers: [
        {
          provide: MODAL_DATA,
          useValue: data
        },
        {
          provide: ModalRef,
          useValue: {
            close: vi.fn()
          }
        }
      ]
    }).compileComponents();

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

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

    expect(element.textContent).toContain(data.content);
    expect(element.textContent).toContain(data.confirmLabel);
    expect(buttons[1].className).toContain('btn-danger');
  });

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

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

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

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

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

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