import get from 'lodash/get';
import formatNumber from "../../../../../utils/election/formatNumber/index.js";
import cx from "../../../../../utils/css/cx.js";
import classes from './styles.module.scss';
const cls = cx.merge(classes);
const Label = props => {
  const {
    number = 0,
    name,
    isWinner = false,
    isUserWinner = false
  } = props;
  const num = formatNumber(number);
  const ways = number === 1 ? 'way' : 'ways';
  if (isWinner) {
    return <span>
        {`${name} wins`}
      </span>;
  }
  if (isUserWinner) {
    return <span>
        {`${name} would win`}
      </span>;
  }
  return <span>
      <span className={cls('sr-only')}>
        {name}
        :
        {' '}
      </span>
      {`${num} ${ways} to win`}
    </span>;
};
const Bar = function Bar(props) {
  const {
    paths = {},
    totals,
    labelPosition = 'top',
    deemphasize,
    candidates,
    liveRegionId,
    isWinner
  } = props;
  const total = paths.dem + paths.gop || 1;
  const winner = (() => {
    if (get(totals, 'dem', 0) >= 270) return 'dem';
    if (get(totals, 'gop', 0) >= 270) return 'gop';
    return undefined;
  })();
  const isTie = paths.dem + paths.gop === 0 && !winner;
  const getPct = party => {
    if (winner === party) return 100;
    if (winner) return 0;
    return get(paths, party, 0) / total * 100;
  };
  const demPct = getPct('dem');
  const gopPct = getPct('gop');
  return <div className={cls('container', labelPosition, {
    winner,
    deemphasize
  })} id={liveRegionId} aria-live="polite" aria-atomic="true">
      <div className={classes.bar}>
        <div className={cls('section', 'dem', {
        isZero: !demPct
      })} style={{
        '--pct': `${demPct}%`
      }} />
        <div className={cls('section', 'tie', {
        isTie
      })}>
          Tied
        </div>
        <div className={cls('section', 'gop', {
        isZero: !gopPct
      })} style={{
        '--pct': `${gopPct}%`
      }} />
      </div>

      <div className={cls('label', 'dem', `winner-${winner}`)}>
        <Label number={paths.dem} name={get(candidates, 'dem.name', 'Dem')} isUserWinner={winner === 'dem'} isWinner={isWinner} />
      </div>

      <div className={cls('label', 'gop', `winner-${winner}`)}>
        <Label number={paths.gop} name={get(candidates, 'gop.name', 'GOP')} isUserWinner={winner === 'gop'} isWinner={isWinner} />
      </div>
    </div>;
};
export default Bar;