import { atom, useAtomValue, useSetAtom } from "@/lib/atom";
import { useLayoutEffect, useRef } from "react";

const NavItems = atom<React.ReactNode>(null);

// eslint-disable-next-line react-refresh/only-export-components
export function useNavItems() {
    return useAtomValue(NavItems);
}

export function PageNavItem({items, children}:{items: React.ReactNode, children: React.ReactNode}) {
    const currentNavItems = useAtomValue(NavItems);
    const setNavItems = useSetAtom(NavItems);
    const prevValueRef = useRef<React.ReactNode>(null);
    
    useLayoutEffect(() => {
        // Store current value before setting new one
        prevValueRef.current = currentNavItems;
        setNavItems(items);
        
        return () => {
            setNavItems(prevValueRef.current);
        };
    }, [items, currentNavItems, setNavItems]);

    return children;
}

