import React from 'react';
import { usePollStats } from '../polling/usePollStats';

type EventStatsContextValue = ReturnType<typeof usePollStats> & {
  eventKey: string;
  slug: string;
};

const EventStatsContext = React.createContext<EventStatsContextValue | undefined>(undefined);

export function EventStatsProvider({ eventKey, children }: { eventKey: string; children: React.ReactNode }) {
  const stats = usePollStats(eventKey);
  const value = React.useMemo<EventStatsContextValue>(
    () => ({ eventKey, slug: eventKey, ...stats }),
    [eventKey, stats]
  );
  return <EventStatsContext.Provider value={value}>{children}</EventStatsContext.Provider>;
}

export function useEventStats() {
  const ctx = React.useContext(EventStatsContext);
  if (!ctx) {
    throw new Error('useEventStats must be used within an EventStatsProvider');
  }
  return ctx;
}

export function useOptionalEventStats() {
  return React.useContext(EventStatsContext);
}
