import '@angular/compiler';
import { TestBed } from '@angular/core/testing';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';

import { GlobalLoadingService } from './global-loading.service';

describe('GlobalLoadingService', () => {
  let service: GlobalLoadingService;

  beforeEach(() => {
    vi.useFakeTimers();
    TestBed.configureTestingModule({});
    service = TestBed.inject(GlobalLoadingService);
  });

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

  it('delays the loading state to avoid flashes on fast operations', () => {
    service.start();

    expect(service.isLoading()).toBe(false);

    service.stop();
    vi.advanceTimersByTime(150);

    expect(service.isLoading()).toBe(false);
  });

  it('shows the loading state for an operation that exceeds the delay', () => {
    service.start();
    vi.advanceTimersByTime(150);

    expect(service.isLoading()).toBe(true);

    service.stop();

    expect(service.isLoading()).toBe(false);
  });

  it('stays visible until all concurrent operations finish', () => {
    service.start();
    service.start();
    vi.advanceTimersByTime(150);

    service.stop();
    expect(service.isLoading()).toBe(true);

    service.stop();
    expect(service.isLoading()).toBe(false);
  });

  it('ignores extra stop calls without corrupting the counter', () => {
    service.stop();
    service.start();
    vi.advanceTimersByTime(150);

    expect(service.isLoading()).toBe(true);

    service.stop();
    expect(service.isLoading()).toBe(false);
  });
});
