// hooks/usePLP.ts
import { useState, useEffect, useRef, useCallback } from 'react';
import { refine } from '@/lib/refine';
export function usePLP(plpId: string) {
const [products, setProducts] = useState<any[]>([]);
const [isLoading, setIsLoading] = useState(true);
const [error, setError] = useState<Error | null>(null);
const contextRef = useRef<any>(null);
useEffect(() => {
setIsLoading(true);
refine.plp.get(plpId)
.then(plp => {
setProducts(plp.results);
contextRef.current = refine.events.trackItemsServed({
surface: 'category_page',
source: 'plp',
itemIds: plp.results.map(p => p.productId),
totalResults: plp.totalResults,
metadata: { plpId }
});
})
.catch(setError)
.finally(() => setIsLoading(false));
}, [plpId]);
const trackClick = useCallback((productId: string, position: number) => {
contextRef.current?.trackClick(productId, position);
}, []);
return { products, isLoading, error, trackClick };
}