import { useContestResults } from "../../../hooks/election/index.js";
import { useMemo } from 'react';
const getCandidateToShow = ({
  party,
  candidates,
  winningCandidate,
  candidateResults
}) => {
  const cand = candidates.reduce((result, current) => {
    const currentParty = current.caucusesWithParty || current.party;
    if (currentParty !== party) {
      return result;
    }
    const {
      id
    } = current;
    const {
      votesPercent
    } = candidateResults[id];
    const currentData = {
      party: currentParty,
      shortName: current.shortName,
      editorialOrder: current.editorialOrder,
      votesPercent
    };
    if (!result) {
      return currentData;
    }
    const {
      id: prevId
    } = result;
    const prevPercent = result.votesPercent;
    if (id === winningCandidate) {
      // If there's a winner, show the winner
      return currentData;
    }
    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 currentData;
    }
    if (votesPercent > prevPercent) {
      // Break ties by picking the candidate with the most votes
      return currentData;
    }
    return result;
  }, undefined);
  const defaultValue = {
    party,
    shortName: undefined,
    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',
      disableFlipCount: true,
      bop: {
        bop: {
          calledDem: demCandidate.votesPercent,
          calledGop: gopCandidate.votesPercent,
          notCalled: 1 - demCandidate.votesPercent - gopCandidate.votesPercent
        },
        winner: outcome !== 'winner' ? undefined : {
          party: winningParty
        }
      }
    };
  }, [results]);
};
export default useSingleContestBopConfig;