import get from 'lodash/get';
import getStateName from "../getStateName/index.js";
import getOfficeName from "../getOfficeName/index.js";
import getCandidateName from "../getCandidateName/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);
  const stateAp = getStateName(fips, {
    format: 'ap_abbr'
  });
  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 holdingParty = get(contestMetadata, 'holdingParty');
  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 getPartyAdj = party => {
    if (['president', 'senate'].includes(office)) return undefined;
    const adjectives = {
      dem: 'Democrat',
      gop: 'Republican'
    };
    return adjectives[party];
  };
  if (isWinner) {
    const winnerName = getCandidateName(winnerMeta);
    const winnerParty = getPartyAdj(winnerMeta.party);
    const isFlip = ['dem', 'gop'].includes(winnerMeta.party) && holdingParty && holdingParty !== winnerMeta.party;
    const verbs = isFlip ? 'flips' : 'wins';
    if (office === 'president') {
      return autohed`${winnerName} ${verbs} ${stateName}`;
    }
    if (office === 'senate') {
      return autohed`${winnerParty} ${winnerName} ${verbs} ${stateName} Senate seat`;
    }
    return autohed`${winnerParty} ${winnerName} elected ${stateName} ${officeName}`;
  }
  if (isLeader) {
    const leaderName = getCandidateName(leaderMeta);
    const leaderParty = getPartyAdj(leaderMeta.party);
    if (office === 'president') {
      return autohed`${leaderName} is ahead in the count in ${stateName}`;
    }
    if (office === 'senate') {
      return autohed`${leaderName} is ahead in the count for ${stateName} Senate seat`;
    }
    return autohed`${stateAp} ${officeName}: ${leaderParty} ${leaderName} ahead in count`;
  }
  if (office === 'president') {
    return autohed`${stateName} presidential election results`;
  }
  return autohed`${stateName} ${officeName} election results`;
};
export default statePageTopper;