import { useContestResults } from "../../../hooks/election/index.js";
import { useMemo } from 'react';
const getCandidateToShow = ({
  party,
  candidates,
  winningCandidate,
  candidateResults
}) => {
  const cand = candidates.reduce((result, current) => {
    if (current.party !== party) {
      return result;
    }
    const {
      id
    } = current;
    const {
      votesPercent
    } = candidateResults[id];
    if (!result) {
      return {
        ...current,
        votesPercent
      };
    }
    const {
      id: prevId
    } = result;
    const prevPercent = result.votesPercent;
    if (id === winningCandidate) {
      // If there's a winner, show the winner
      return {
        ...current,
        votesPercent
      };
    }
    if (winningCandidate && prevId === winningCandidate) {
      // If there's a winner, show the winner
      return result;
    }
    if (current.editorialOrder < result.editorialOrder) {
      // Otherwise, pick the candidate from the party with the most important `editorialOrder`
      return {
        ...current,
        votesPercent
      };
    }
    if (votesPercent > prevPercent) {
      // Break ties by picking the candidate with the most votes
      return {
        ...current,
        votesPercent
      };
    }
    return result;
  }, undefined);
  const defaultValue = {
    party,
    editorialOrder: 0,
    votesPercent: 0
  };
  return cand || defaultValue;
};
const useSingleContestBopConfig = contestId => {
  const results = useContestResults(contestId);
  if (!results) {
    return undefined;
  }
  return useMemo(() => {
    const {
      candidates,
      candidateResults,
      contestStatus: {
        outcome,
        winningParty,
        winningCandidate
      }
    } = results;
    const demCandidate = getCandidateToShow({
      party: 'dem',
      candidates,
      winningCandidate,
      candidateResults
    });
    const gopCandidate = getCandidateToShow({
      party: 'gop',
      candidates,
      winningCandidate,
      candidateResults
    });
    return {
      demName: demCandidate.shortName,
      gopName: gopCandidate.shortName,
      mode: 'grouped',
      labelFormat: 'percent',
      bop: {
        bop: {
          calledDem: demCandidate.votesPercent,
          calledGop: gopCandidate.votesPercent,
          notCalled: 1 - demCandidate.votesPercent - gopCandidate.votesPercent
        },
        winner: outcome !== 'winner' ? undefined : {
          party: winningParty
        }
      }
    };
  }, [results]);
};
export default useSingleContestBopConfig;