/* eslint-disable react/no-array-index-key */
import { useMemo } from 'react';
import cx from "../../../../utils/css/cx.js";
import { useContainerResponsiveValues } from "../../../../hooks/breakpoint/index.js";
import sortBy from "../../../../utils/sorting/sortBy.js";
import classes from './styles.module.scss';
import Dot from './Dot';
import scaleDots from '../utils/scaleDots';
import createArray from '../utils/createArray';
const cls = cx.merge(classes);
export default function DelegateDots({
  eventState
}) {
  const delegates = useMemo(() => {
    const allDel = createArray(eventState.total, {});
    const {
      candidates
    } = eventState;
    // Get non-zero candidates
    const filldCands = candidates.filter(d => d.total > 0);
    const sortedCands = sortBy(filldCands, [{
      comparison: 'total',
      direction: 'desc'
    }, {
      comparison: 'id',
      direction: 'desc'
    }]);

    // Create dots for each delegate
    const delDots = sortedCands.map(d => {
      const arr = createArray(d.total, {
        id: d.id,
        total: d.total
      });
      return arr;
    }).flat();
    return [...delDots, ...allDel.slice(delDots.length)];
  }, [eventState]);

  // Used to control the scaling factor on the dots
  // The larger the number, the larger the circles will
  // be allowed to be for states that have > 100 delegates
  const inputMax = useContainerResponsiveValues({
    xxs: 80,
    xs: 100,
    lg: 200,
    xxl: 400
  });
  return <div className={cls('dots-container')} style={{
    '--size': `${scaleDots(delegates.length, inputMax)}px`
  }}>
      {delegates.map((d, i) => <Dot data={d?.id} key={`${d?.id || 'empty'}-${i}`} />)}
    </div>;
}