import get from 'lodash/get';
import getStateName from "../getStateName/index.js";
import getOfficeName from "../getOfficeName/index.js";
import getCandidateName from "../getCandidateName/index.js";
import getPartyName from "../getPartyName/index.js";
import autohed from './autohed';
const statePageTopper = function statePageTopper(opts) {
  const {
    stateFips,
    isHouse,
    status,
    contestMetadata,
    candidates = []
  } = opts;
  const fips = get(contestMetadata, 'stateFips', stateFips);
  const stateName = getStateName(fips);
  if (isHouse) {
    return autohed`${stateName} House election results`;
  }
  const candidatesById = Object.fromEntries(candidates.map(c => [c.id, c]));
  const office = get(contestMetadata, 'office');
  const isRunoff = get(status, 'outcome') === 'runoff';
  const winnerId = get(status, 'winningCandidate');
  const winnerMeta = get(candidatesById, winnerId);
  const isWinner = get(status, 'outcome') === 'winner' && !!winnerMeta;
  const leaderId = get(status, 'leadingCandidate');
  const leaderMeta = get(candidatesById, leaderId);
  const isLeader = !!leaderMeta;
  const officeName = getOfficeName(office);
  if (isRunoff) {
    if (office === 'president') {
      return autohed`Presidential election in ${stateName} goes to runoff`;
    }
    return autohed`${officeName} election in ${stateName} goes to runoff`;
  }
  const getPartyParen = party => {
    if (['president', 'senate', 'governor'].includes(office)) return undefined;
    return getPartyName(party, {
      format: 'letter-parenthesis'
    });
  };
  if (isWinner) {
    const winnerName = getCandidateName(winnerMeta);
    const winnerParty = getPartyParen(winnerMeta.party);
    if (office === 'president') {
      return autohed`${winnerName} wins presidential election in ${stateName}`;
    }
    return autohed`${winnerName} ${winnerParty} wins race for ${officeName} in ${stateName}`;
  }
  if (isLeader) {
    const leaderName = getCandidateName(leaderMeta);
    const leaderParty = getPartyParen(leaderMeta.party);
    return autohed`${leaderName} ${leaderParty} leads race for ${officeName} in ${stateName}`;
  }
  if (office === 'president') {
    return autohed`${stateName} presidential election results`;
  }
  return autohed`${stateName} ${officeName} election results`;
};
export default statePageTopper;