import { jsx as _jsx } from "react/jsx-runtime";
// (C) 2025 GoodData Corporation
import { createContext, useCallback, useContext, useEffect, useState, } from "react";
import { EventEmitter } from "./eventEmitter.js";
const EventsContext = createContext(null);
/**
 * @internal
 */
export function UiTreeViewEventsProvider({ children }) {
    // Only create the emitter once
    const [emitter] = useState(() => new EventEmitter());
    return _jsx(EventsContext.Provider, { value: emitter, children: children });
}
/**
 * @internal
 */
export function useUiTreeViewEventPublisher(eventType) {
    const emitter = useContext(EventsContext);
    return useCallback((event) => {
        emitter?.emit(eventType, event);
    }, [eventType, emitter]);
}
/**
 * @internal
 */
export function useUiTreeViewEventSubscriber(eventType, handler) {
    const emitter = useContext(EventsContext);
    useEffect(() => {
        if (!emitter) {
            return undefined;
        }
        emitter.on(eventType, handler);
        return () => {
            emitter.off(eventType, handler);
        };
    }, [emitter, eventType, handler]);
}
