import { isPlatformBrowser } from '@angular/common';
import { Injectable, PLATFORM_ID, inject, signal } from '@angular/core';

const SHOW_DELAY_MS = 150;

@Injectable({ providedIn: 'root' })
export class GlobalLoadingService {
  private readonly isBrowser = isPlatformBrowser(inject(PLATFORM_ID));
  private readonly loadingState = signal(false);
  private pendingOperations = 0;
  private showTimer: ReturnType<typeof setTimeout> | undefined;

  readonly isLoading = this.loadingState.asReadonly();

  start(): void {
    if (!this.isBrowser) {
      return;
    }

    this.pendingOperations += 1;

    if (this.pendingOperations > 1 || this.loadingState()) {
      return;
    }

    this.showTimer = setTimeout(() => {
      this.showTimer = undefined;

      if (this.pendingOperations > 0) {
        this.loadingState.set(true);
      }
    }, SHOW_DELAY_MS);
  }

  stop(): void {
    if (!this.isBrowser || this.pendingOperations === 0) {
      return;
    }

    this.pendingOperations -= 1;

    if (this.pendingOperations > 0) {
      return;
    }

    this.cancelShowTimer();
    this.loadingState.set(false);
  }

  private cancelShowTimer(): void {
    if (this.showTimer === undefined) {
      return;
    }

    clearTimeout(this.showTimer);
    this.showTimer = undefined;
  }
}
