import { useMemo } from 'react';
import get from 'lodash/get';
import { bodyHeadline } from "../../../utils/election/index.js";
import { useBops } from "../../../hooks/election/index.js";
import { useNowInterval } from "../../../hooks/time/index.js";
export default function useBopCalls(opts = {}) {
  const {
    bopIds = ['president', 'senate', 'house'],
    nowInterval = 5000,
    recentWindow = 5 * 60000 // 5m
  } = opts;
  const bops = useBops();
  const now = useNowInterval(nowInterval);
  const allCalls = useMemo(() => {
    if (!bops) return [];
    const calledBops = bopIds.map(id => ({
      office: id,
      bop: bops[id]
    })).filter(bop => !!bop.bop.call);
    const calls = calledBops.map(bop => {
      const timestamp = get(bop.bop.call, 'timestamp');
      const party = get(bop.bop, 'winner.party');
      const link = `index:${bop.office}`;
      const text = bodyHeadline({
        office: bop.office,
        bop: bop.bop
      });
      if (!text || !party || !['dem', 'gop'].includes(party)) {
        return undefined;
      }
      return {
        timestamp,
        office: bop.office,
        party,
        link,
        text,
        feedType: 'bop'
      };
    }).filter(Boolean);
    return calls;
  }, [bops, ...bopIds]);
  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)).slice(0, 1);
  }, [allCalls, now, recentWindow]);
  return {
    recentCalls,
    allCalls
  };
}