"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,
    hasBookingFlowParamsChanged,
  } = useTrackingStore()

  const { startRouterTransition } = useRouterTransitionStore()

  useEffect(() => {
    if (pathName.includes("payment-callback")) {
      return
    }

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

  return null
}
