import { useMemo } from 'react';
import { useNowInterval } from "../../../hooks/time/index.js";
import usePollClosingTimes from "../../../hooks/election/usePollClosingTimes/index.js";
import getSoonCartoProps from './getSoonCartoProps';
import getGradientCartoProps from './getGradientCartoProps';
const useCartoProps = function useCartoProps({
  mode
}) {
  const pollClosingTimes = usePollClosingTimes();
  const currentTime = useNowInterval(60000);
  const closingTimes = useMemo(() => {
    const times = {
      byState: new Map(),
      first: undefined
    };
    const getEarlierTime = (t1, t2) => {
      if (!t1) return t2;
      if (!t2) return t1;
      return t1 < t2 ? t1 : t2;
    };
    pollClosingTimes.forEach(event => {
      const states = [...event.partiallyClosed, ...event.fullyClosed];
      states.forEach(stateFips => {
        const old = times.byState.get(stateFips);
        times.byState.set(stateFips, getEarlierTime(old, event.date));
      });
      times.first = getEarlierTime(times.first, event.date);
    });
    return times;
  }, [pollClosingTimes]);
  return useMemo(() => {
    const timeToFirst = new Date(closingTimes.first).getTime() - currentTime;
    const minsToFirst = Math.round(timeToFirst / (1000 * 60));
    const isSoon = mode === 'auto' && minsToFirst < 60 || mode === 'soon';
    if (isSoon) {
      const soonCartoProps = getSoonCartoProps({
        pollClosingTimes,
        currentTime
      });
      return {
        isSoon,
        legendProps: {},
        cartoProps: soonCartoProps
      };
    }
    const gradientCartoProps = getGradientCartoProps({
      closingTimes
    });
    return {
      isSoon,
      legendProps: gradientCartoProps.legendProps,
      cartoProps: gradientCartoProps.cartoProps
    };
  }, [currentTime, closingTimes]);
};
export default useCartoProps;