import NProgress from 'nprogress'

let activeRequests = 0

function startRequest() {
  activeRequests++
  if (activeRequests === 1) {
    NProgress.start()
  }
}

function endRequest() {
  if (activeRequests > 0) {
    activeRequests--
    if (activeRequests === 0) {
      NProgress.done()
    }
  }
}

export class ApiClient {
  private static instance: ApiClient

  private constructor() {}

  static getInstance(): ApiClient {
    if (!ApiClient.instance) {
      ApiClient.instance = new ApiClient()
    }
    return ApiClient.instance
  }

  async fetch<T>(url: string, options?: RequestInit): Promise<T> {
    try {
      startRequest()
      const response = await fetch(url, options)

      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`)
      }

      const data = await response.json()
      return data as T
    } catch (error) {
      console.error('API request failed:', error)
      throw error
    } finally {
      endRequest()
    }
  }

  async simulateLoading<T>(data: T, delay: number = 500): Promise<T> {
    try {
      startRequest()
      await new Promise(resolve => setTimeout(resolve, delay))
      return data
    } finally {
      endRequest()
    }
  }
}

export const apiClient = ApiClient.getInstance()
