/**
* Hook for fetching and managing seat data from the GraphQL API
*/
import { useQuery } from '@apollo/client';
import { useMemo } from 'react';
import { GET_SEATS_BY_PROVINCE_AND_PARTY } from '@/lib/queries';
import {
ProvinceSeatData,
ProvinceSeatCount,
processApiSeatData,
calculateNationalTotals,
getSeatBreakdown as getSeatBreakdownUtil,
getDominantParty as getDominantPartyUtil,
getProvinceSeatData as getProvinceSeatDataUtil,
getTotalSeats,
} from '@/lib/visualizer/seatData';
interface SeatDataResult {
seatsByProvinceAndParty: ProvinceSeatCount[];
}
export function useSeatData() {
const { data, loading, error } = useQuery<SeatDataResult>(
GET_SEATS_BY_PROVINCE_AND_PARTY,
{
// Cache for 5 minutes since seat data doesn't change often
fetchPolicy: 'cache-first',
}
);
// Process the API data into the format used by the visualizer
const seatData = useMemo<Record<string, ProvinceSeatData>>(() => {
if (!data?.seatsByProvinceAndParty) {
return {};
}
return processApiSeatData(data.seatsByProvinceAndParty);
}, [data]);
// Calculate national totals
const nationalTotals = useMemo(() => {
return calculateNationalTotals(seatData);
}, [seatData]);
// Calculate total seats
const totalSeats = useMemo(() => {
return getTotalSeats(seatData);
}, [seatData]);
// Helper functions that work with the current seatData
const getSeatBreakdown = (provinceCode: string) => {
return getSeatBreakdownUtil(seatData, provinceCode);
};
const getDominantParty = (provinceCode: string) => {
return getDominantPartyUtil(seatData, provinceCode);
};
const getProvinceSeatData = (provinceCode: string) => {
return getProvinceSeatDataUtil(seatData, provinceCode);
};
return {
seatData,
nationalTotals,
totalSeats,
loading,
error,
getSeatBreakdown,
getDominantParty,
getProvinceSeatData,
};
}