// 类型声明
type LoadingControllerConfig = {
  minDisplayTime?: number;
  fadeDuration?: number;
};

export class LoadingController {
  private overlay: HTMLElement;
  private startTime = 0;
  private config: Required<LoadingControllerConfig>;

  constructor(config: LoadingControllerConfig = {}) {
    this.overlay = document.getElementById('loading-overlay')!;
    this.config = {
      minDisplayTime: 500,
      fadeDuration: 300,
      ...config
    };
  }

  // 显示加载状态
  show(): void {
    this.startTime = Date.now();
    this.overlay.classList.add('active');
  }

  // 隐藏加载状态（带最小显示时间保证）
  async hide(): Promise<void> {
    const elapsed = Date.now() - this.startTime;
    const remainingTime = Math.max(this.config.minDisplayTime - elapsed, 0);

    await new Promise(resolve =>
      setTimeout(resolve, remainingTime)
    );

    this.overlay.classList.remove('active');

    // 等待动画完成
    await new Promise(resolve =>
      setTimeout(resolve, this.config.fadeDuration)
    );
  }

  // 包装异步操作
  async wrap<T>(promise: Promise<T>): Promise<T> {
    try {
      this.show();
      return await promise;
    } finally {
      await this.hide();
    }
  }
}