import { getSeason, SeasonParticipant } from "@/apis/seasonApi"; import React, { createContext, ReactNode, useCallback, useContext, useState, } from "react"; type SeasonContextType = { fetchSeasonParticipants: ( showId: number, seasonNumber: number ) => Promise; fetchSeasonCount: (showId: number) => Promise; }; const SeasonContext = createContext(null); export const SeasonProvider = ({ children }: { children: ReactNode }) => { const [seasonCache, setSeasonCache] = useState< Record >({}); const [seasonCountCache, setSeasonCountCache] = useState< Record >({}); const fetchSeasonParticipants = useCallback( async (showId: number, seasonNumber: number) => { const key = `${showId}-${seasonNumber}`; if (seasonCache[key]) return seasonCache[key]; try { const season = await getSeason(showId, seasonNumber); const participants = season?.participants ?? []; setSeasonCache((c) => ({ ...c, [key]: participants })); return participants; } catch { return []; } }, [seasonCache] ); const fetchSeasonCount = useCallback( async (showId: number) => { if (seasonCountCache[showId] !== undefined) return seasonCountCache[showId]; let n = 0; for (let s = 1; s <= 50; s++) { try { const season = await getSeason(showId, s); if (!season) break; n = s; } catch { break; } } setSeasonCountCache((c) => ({ ...c, [showId]: n })); return n; }, [seasonCountCache] ); return ( {children} ); }; export const useSeasonContext = () => { const ctx = useContext(SeasonContext); if (!ctx) throw new Error("useSeasonContext must be used within a SeasonProvider"); return ctx; };