import { useMemo } from 'react';
import { useContestCollectionContests } from "../index.js";
const useContestDistrictMapColors = function useContestDistrictMapColors({
  collectionId
}) {
  const districtsData = useContestCollectionContests(collectionId);
  const contestIds = districtsData ? Object.keys(districtsData) : [];
  return useMemo(() => {
    const statuses = contestIds.reduce((status, contestId) => {
      const district = districtsData[contestId];
      const {
        combinedMetadata: districtMeta,
        contestStatus,
        candidateColors
      } = district;
      console.log(districtMeta, 'meta');
      const {
        leadingCandidate,
        winningCandidate
      } = contestStatus;
      const {
        contest: {
          districtNumber,
          stateFips
        }
      } = districtMeta;
      const candidateId = winningCandidate || leadingCandidate;
      const palette = candidateColors && candidateColors[candidateId];
      const isAtLarge = contestIds.length === 1;
      const code = isAtLarge ? `${stateFips}00` : `${stateFips}${districtNumber}`;
      status.fipsToPalette.set(code, {
        code,
        status: contestStatus,
        candidateId,
        contestId,
        palette
      });
      if (palette) {
        status.palettes.set(contestId, palette);
      }
      return {
        ...status,
        includeNoClearLeader: status.includeNoClearLeader || contestStatus === 'unclear',
        includeRunoff: status.outcome === 'runoff'
      };
    }, {
      fipsToPalette: new Map(),
      palettes: new Map(),
      includeNoClearLeader: false,
      includeRunoff: false
    });
    return {
      ...statuses,
      palettes: [...statuses.palettes].map(([contestId, palette]) => ({
        contestId,
        palette
      }))
    };
  }, [districtsData]);
};
export default useContestDistrictMapColors;