import React, { createContext, useContext, useMemo } from "react";
import { useEvents } from "../hooks/use-events";
import type { InstanceEventPayload } from "../types/events";

interface EventContextValue {
	events: InstanceEventPayload[];
	connected: boolean;
	reconnectCount: number;
}

const EventContext = createContext<EventContextValue>({
	events: [],
	connected: false,
	reconnectCount: 0,
});

export function EventProvider({ children }: { children: React.ReactNode }) {
	const { events, connected, reconnectCount } = useEvents();
	const value = useMemo(
		() => ({ events, connected, reconnectCount }),
		[events, connected, reconnectCount],
	);
	return (
		<EventContext.Provider value={value}>{children}</EventContext.Provider>
	);
}

export function useEventContext() {
	return useContext(EventContext);
}
