"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 { trackEvent } from "@scandic-hotels/tracking/base"

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

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

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

  const { startRouterTransition } = useRouterTransitionStore()

  useEffect(() => {
    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,
  ])

  // Track login success if loginPosition param is present. The LoginButton component has a
  // loginPosition prop that adds this param to the URL upon successful login.
  useEffect(() => {
    const loginPosition = searchParams.get("loginPosition")
    if (loginPosition) {
      trackEvent({
        event: "loginSuccess",
        login: {
          position: loginPosition,
          pathName,
        },
      })

      const params = new URLSearchParams(searchParams)
      params.delete("loginPosition")
      const search = params.toString()
      const newUrl = search ? `${pathName}?${search}` : pathName
      window.history.replaceState(null, "", newUrl)
    }
  }, [pathName, searchParams])

  return null
}
