import { useEffect, useState } from "react"
import Nanobar from "nanobar"

function useProgress() {
  const [bar, setBar] = useState()

  useEffect(() => {
    let container = document.querySelector("#design-progress")

    if (!container) {
      container = document.createElement("div")
      container.id = "design-progress"
      container.style.position = "fixed"
      container.style.width = "100%"
      container.style.top = 0
      document.body.appendChild(container)
    }

    const nanobar = new Nanobar({
      target: container,
      classname: "design-progress",
    })
    nanobar.el.style.position = "fixed"

    const progress = {
      go: nanobar.go,
      finish: () => {
        nanobar.go(100)
      },
    }

    setBar(progress)

    return () => {
      nanobar.el.remove()
    }
  }, [])

  return bar
}

export default useProgress