"use client"

import { startTransition, useEffect, useOptimistic } from "react"

import useRouterTransitionStore from "@/stores/router-transition"

export default function RouterTransition() {
  const [loading, setLoading] = useOptimistic(false)
  const { isTransitioning, stopRouterTransition } = useRouterTransitionStore()

  useEffect(() => {
    if (!isTransitioning) {
      return
    }

    if (isTransitioning) {
      startTransition(() => {
        setLoading(true)
      })
    }

    if (!loading && isTransitioning) {
      stopRouterTransition()

      // Send event to adobe that navigation transition is completed
      if (window.adobeDataLayer) {
        window.adobeDataLayer.push({
          event: "pageViewEnd",
        })
      }
    }
  }, [isTransitioning, setLoading, loading, stopRouterTransition])

  return null
}
