import { useMemo } from 'react';
import get from 'lodash/get';
import { getContestLink, raceCall } from "../../../utils/election/index.js";
import { useCallFeed } from "../../../hooks/election/index.js";
import { useNowInterval } from "../../../hooks/time/index.js";
export default function useFeedCalls(opts) {
  const {
    collectionId,
    nowInterval = 5000,
    recentWindow = 5 * 60000 // 5m
  } = opts;
  const feed = useCallFeed(collectionId);
  const now = useNowInterval(nowInterval);
  const allCalls = useMemo(() => {
    if (!feed) return [];
    const calls = feed.calls.map((entry, i) => {
      const {
        call,
        contestMetadata,
        candidateMetadata
      } = entry;
      const id = get(contestMetadata, 'id');
      const timestamp = get(call, 'timestamp');
      const party = get(candidateMetadata, 'party');
      const holdingParty = get(contestMetadata, 'party');
      const link = getContestLink(contestMetadata);
      const text = raceCall(entry);
      const office = get(contestMetadata, 'office');
      const callType = get(call, 'type');
      const isFlip = !!holdingParty && ['dem', 'gop'].includes(party) && party !== holdingParty;
      if (callType !== 'winner') return undefined;
      if (!text) return undefined;
      return {
        id: `${id}-${i}`,
        timestamp,
        office,
        party,
        holdingParty,
        isFlip,
        link,
        text,
        feedType: 'races'
      };
    }).filter(Boolean);
    return calls;
  }, [feed]);
  const recentCalls = useMemo(() => {
    const nowDate = new Date(now);
    const recent = allCalls.filter(call => nowDate - new Date(call.timestamp) < recentWindow);
    return recent.sort((a, b) => b.timestamp.localeCompare(a.timestamp));
  }, [allCalls, now, recentWindow]);
  return {
    recentCalls,
    allCalls
  };
}