import { ref } from 'vue'

const isGlobalLoading = ref(false)
let loadingStartTime = null

export const useLoading = () => {
  const showLoading = () => {
    isGlobalLoading.value = true
    loadingStartTime = Date.now()
  }

  const hideLoading = () => {
    if (!loadingStartTime) {
      isGlobalLoading.value = false
      return
    }

    // 최소 300ms 동안 로딩을 표시
    const elapsedTime = Date.now() - loadingStartTime
    const minLoadingTime = 300

    if (elapsedTime < minLoadingTime) {
      setTimeout(() => {
        isGlobalLoading.value = false
        loadingStartTime = null
      }, minLoadingTime - elapsedTime)
    } else {
      isGlobalLoading.value = false
      loadingStartTime = null
    }
  }

  return {
    isGlobalLoading,
    showLoading,
    hideLoading
  }
}
