"use client"

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

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

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

export default function RouterTracking() {
  const pathName = usePathname()
  const searchParams = useSearchParams()
  const { setInitialPageLoadTime, hasRun } = useTrackingStore()

  const { startRouterTransition } = useRouterTransitionStore()

  // We need this check to differentiate hard vs soft navigations
  // This is not because of StrictMode
  const hasRunInitial = useRef<boolean>(false)
  const previousPathname = useRef<string | null>(null)

  useEffect(() => {
    if (!hasRunInitial.current) {
      hasRunInitial.current = true
      previousPathname.current = pathName // Set initial path to compare later
      return
    }

    if (previousPathname.current !== pathName) {
      console.log("TRACKING: RESET PAGE LOAD TIME")
      setInitialPageLoadTime(Date.now())
      trackPageViewStart()
      startTransition(() => {
        startRouterTransition()
      })
    }
    previousPathname.current = pathName // Update for next render
  }, [
    pathName,
    searchParams,
    setInitialPageLoadTime,
    startRouterTransition,
    hasRun,
  ])

  return null
}
