"use client"

import { usePathname } from "next/navigation"
import { useEffect, useState, useRef } from "react"
import { motion, AnimatePresence } from "framer-motion"

interface ContentTransitionProps {
  children: React.ReactNode
}

export function ContentTransition({ children }: ContentTransitionProps) {
  const pathname = usePathname()
  const [displayChildren, setDisplayChildren] = useState(children)
  const [direction, setDirection] = useState<"left" | "right">("left")
  const prevPathname = useRef(pathname)

  useEffect(() => {
    // Get swipe direction from sessionStorage (set by swipe navigation)
    const swipeDirection = sessionStorage.getItem("swipeDirection")
    if (swipeDirection === "left" || swipeDirection === "right") {
      setDirection(swipeDirection)
      sessionStorage.removeItem("swipeDirection")
    } else {
      // Determine direction based on pathname change
      const NAV_ORDER = [
        "/feed",
        "/leaders",
        "/messages",
        "/friendlies",
        "/alerts",
        "/profile",
      ]
      const currentIndex = NAV_ORDER.indexOf(pathname.split("?")[0])
      const prevIndex = NAV_ORDER.indexOf(prevPathname.current.split("?")[0])
      
      if (currentIndex !== -1 && prevIndex !== -1) {
        setDirection(currentIndex > prevIndex ? "left" : "right")
      } else {
        setDirection("left")
      }
    }
    
    prevPathname.current = pathname
    // Update children
    setDisplayChildren(children)
  }, [pathname, children])

  const variants = {
    enter: (direction: "left" | "right") => ({
      x: direction === "left" ? "100%" : "-100%",
      opacity: 0,
    }),
    center: {
      x: 0,
      opacity: 1,
    },
    exit: (direction: "left" | "right") => ({
      x: direction === "left" ? "-100%" : "100%",
      opacity: 0,
    }),
  }

  return (
    <div className="relative overflow-hidden w-full min-h-[calc(100vh-4rem)]">
      <AnimatePresence mode="wait" custom={direction} initial={false}>
        <motion.div
          key={pathname}
          custom={direction}
          variants={variants}
          initial="enter"
          animate="center"
          exit="exit"
          transition={{
            x: { type: "spring", stiffness: 300, damping: 30 },
            opacity: { duration: 0.2 },
          }}
          className="w-full"
        >
          {displayChildren}
        </motion.div>
      </AnimatePresence>
    </div>
  )
}

