import { useState, useEffect, useCallback, useRef } from 'react'; import { getBulkTeams, getBulkAthletes } from '@bettoredge/api'; import type { CalcuttaAuctionItemProps } from '@bettoredge/types'; export interface ItemImageMap { [item_id: string]: { url: string } | undefined; } /** * Fetches team/athlete images for calcutta auction items. * Groups items by type (team vs athlete), bulk-fetches from sr_svc, * and returns a map of item_id → image. */ export const useCalcuttaItemImages = (items: CalcuttaAuctionItemProps[]) => { const [images, setImages] = useState({}); const [loading, setLoading] = useState(false); const fetchedRef = useRef>(new Set()); const fetchImages = useCallback(async (auctionItems: CalcuttaAuctionItemProps[]) => { // Separate by type and dedupe against already-fetched const teamIds: string[] = []; const athleteIds: string[] = []; for (const item of auctionItems) { if (!item.item_id || fetchedRef.current.has(item.item_id)) continue; if (item.item_type === 'team') { teamIds.push(item.item_id); } else if (item.item_type === 'athlete') { athleteIds.push(item.item_id); } } if (teamIds.length === 0 && athleteIds.length === 0) return; setLoading(true); const newImages: ItemImageMap = {}; try { const [teamsRes, athletesRes] = await Promise.all([ teamIds.length > 0 ? getBulkTeams({ attribute: 'team_id', values: teamIds }).catch(() => ({ teams: [] })) : { teams: [] }, athleteIds.length > 0 ? getBulkAthletes({ attribute: 'athlete_id', values: athleteIds }).catch(() => ({ athletes: [] })) : { athletes: [] }, ]); for (const team of (teamsRes.teams || [])) { if (team.image?.url) { newImages[team.team_id] = team.image; } fetchedRef.current.add(team.team_id); } for (const athlete of (athletesRes.athletes || [])) { if (athlete.image?.url) { newImages[athlete.athlete_id] = athlete.image; } fetchedRef.current.add(athlete.athlete_id); } if (Object.keys(newImages).length > 0) { setImages(prev => ({ ...prev, ...newImages })); } } catch { // Silently fail — items will show fallback icons } setLoading(false); }, []); useEffect(() => { if (items.length > 0) { fetchImages(items); } }, [items.map(i => i.item_id).join(','), fetchImages]); return { images, loading }; };