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 {
  SimpleModalData,
  MODAL_DATA,
  ModalRef
} from '../../../core/services/modal.service';
import { SimpleModalComponent } from './simple-modal.component';

describe('SimpleModalComponent', () => {
  const data: SimpleModalData = {
    content: 'Este es un mensaje simple.',
    buttonLabel: 'Entendido'
  };

  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 button label', async () => {
    await TestBed.configureTestingModule({
      imports: [SimpleModalComponent],
      providers: [
        {
          provide: MODAL_DATA,
          useValue: data
        },
        {
          provide: ModalRef,
          useValue: {
            close: vi.fn()
          }
        }
      ]
    }).compileComponents();

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

    const element = fixture.nativeElement as HTMLElement;

    expect(element.textContent).toContain(data.content);
    expect(element.textContent).toContain(data.buttonLabel);
  });

  it('closes when clicking the primary button', async () => {
    const closeSpy = vi.fn();

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

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

    const button = fixture.nativeElement.querySelector('button');
    button.click();

    expect(closeSpy).toHaveBeenCalled();
  });
});
