'use client'

import clsx from 'clsx'
import { AnimatePresence, motion } from 'framer-motion'
import { usePathname } from 'next/navigation'
import React, { useRef } from 'react'

type Props = {
  children: React.ReactNode
  className?: string
}

function ClientSideWrapper({ children, className = 'h-full' }: Props) {
  const pathname = usePathname()
  const isFirstMount = useRef(true)
  const prevPathname = useRef(pathname)

  // تشخیص اولین mount
  const isInitial = isFirstMount.current
  if (isFirstMount.current) {
    isFirstMount.current = false
  }

  // تشخیص تغییر pathname
  const pathnameChanged = prevPathname.current !== pathname
  prevPathname.current = pathname

  return (
    <AnimatePresence mode="sync">
      <motion.div
        key={pathname}
        initial={isInitial || !pathnameChanged ? false : { y: -10 }}
        animate={{ y: 0 }}
        exit={{ y: 0, transition: { duration: 0 } }}
        transition={{ duration: 0.12 }}
        style={{ opacity: 1 }}
        className={clsx(className)}
      >
        {children}
      </motion.div>
    </AnimatePresence>
  )
}

export default ClientSideWrapper
