import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import type { Router } from 'vue-router'


NProgress.configure({
  easing: 'ease',
  speed: 500,
  showSpinner: false,
  trickleSpeed: 200,
  minimum: 0.3,
  parent: 'body',
})

let activeRequests = 0

export function setupNProgress(router: Router) {
  function startProgress() {
    activeRequests++
    if (activeRequests === 1) {
      NProgress.start()
    }
  }

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

  router.beforeEach((to, from, next) => {
    if (to.path !== from.path) {
      startProgress()
    }
    next()
  })

  router.afterEach((to, from) => {
    if (to.path !== from.path) {
      setTimeout(stopProgress, 100)
    }
  })

  router.onError((error) => {
    console.error('Router error:', error)
    stopProgress()
  })

  return { startProgress, stopProgress }
}
