"use client"

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

export default function PostHogPageView(): JSX.Element | null {
  const pathname = usePathname()
  const searchParams = useSearchParams()

  useEffect(() => {
    if (pathname === "" || process.env.NODE_ENV !== "production") return

    import("posthog-js").then(({ default: posthog }) => {
      if (!posthog.__loaded) return
      let url = window.origin + pathname
      if (searchParams?.toString()) {
        url = url + `?${searchParams.toString()}`
      }
      posthog.capture("$pageview", { $current_url: url })
    })
  }, [pathname, searchParams])

  return null
}
