"use client"

import { useCart } from '@/app/[name]/(Dialogs)/cart/hook/useCart'
import { useGetProfile } from '@/app/[name]/(Profile)/profile/hooks/userProfileData'
import { useParams } from 'next/navigation'
import { useEffect, useRef, type FC } from 'react'

const CartChecker: FC = () => {

    const { isSuccess } = useGetProfile()
    const params = useParams()
    const currentSlug = params.name as string
    const { slug: cartSlug, clearCart } = useCart()
    const hasClearedRef = useRef(false)

    useEffect(() => {
        if (!isSuccess && currentSlug && cartSlug && currentSlug !== cartSlug) {
            if (!hasClearedRef.current) {
                hasClearedRef.current = true
                clearCart()
            }
        } else if (currentSlug === cartSlug) {
            hasClearedRef.current = false
        }
    }, [isSuccess, currentSlug, cartSlug, clearCart])

    return null
}

export default CartChecker