"use client"

import { usePathname, useSearchParams } from "next/navigation"
import { startTransition, useEffect } from "react"

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

import { trackPageViewStart } from "@/utils/tracking"

export default function RouterTracking({ children }: React.PropsWithChildren) {
  const pathName = usePathname()
  const searchParams = useSearchParams()
  const { setInitialPageLoadTime, hasRun } = useTrackingStore()

  const { startRouterTransition } = useRouterTransitionStore()

  useEffect(() => {
    if (hasRun) {
      setInitialPageLoadTime(Date.now())
      trackPageViewStart()
      startTransition(() => {
        startRouterTransition()
      })
    }
  }, [
    pathName,
    searchParams,
    setInitialPageLoadTime,
    startRouterTransition,
    hasRun,
  ])

  return <>{children}</>
}
