"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 useLang from "@/hooks/useLang"
import { trackPageViewStart } from "@/utils/tracking"

export default function RouterTracking() {
  const pathName = usePathname()
  const searchParams = useSearchParams()
  const currentLang = useLang()

  const { setInitialPageLoadTime, updateRouteInfo, hasPathOrLangChanged } =
    useTrackingStore()

  const { startRouterTransition } = useRouterTransitionStore()

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

  return null
}
