"use client"

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

import { isSameBookingWidgetParams } from "@scandic-hotels/booking-flow/utils/isSameBooking"
import useRouterTransitionStore from "@scandic-hotels/common/stores/router-transition"
import useTrackingStore from "@scandic-hotels/common/stores/tracking"
import { trackPageViewStart } from "@scandic-hotels/tracking/pageview"

import useLang from "@/hooks/useLang"

export default function RouteChange() {
  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()) {
      // Scroll to top on page load whenever page is navigated to new URL (page)
      window.scrollTo({ top: 0, left: 0, behavior: "instant" })
    }

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

  return null
}
