"use client";
import { jsx } from "react/jsx-runtime";
import { createContext, useCallback, useContext, useEffect, useMemo, useState } from "react";
import { useLexicalComposerContext } from "@lexical/react/LexicalComposerContext";
import { COMMAND_PRIORITY_CRITICAL, SELECTION_CHANGE_COMMAND } from "lexical";
const ToolbarExtensionsContext = /*#__PURE__*/ createContext(null);
function ToolbarExtensionsProvider({ children }) {
    const [rootEditor] = useLexicalComposerContext();
    const [activeEditor, setActiveEditor] = useState(rootEditor);
    const [itemsById, setItemsById] = useState(()=>new Map());
    useEffect(()=>rootEditor.registerCommand(SELECTION_CHANGE_COMMAND, (_payload, newEditor)=>{
            setActiveEditor(newEditor);
            return false;
        }, COMMAND_PRIORITY_CRITICAL), [
        rootEditor
    ]);
    const register = useCallback((item)=>{
        setItemsById((prev)=>{
            const next = new Map(prev);
            next.set(item.id, item);
            return next;
        });
        return ()=>{
            setItemsById((prev)=>{
                if (!prev.has(item.id)) return prev;
                const next = new Map(prev);
                next.delete(item.id);
                return next;
            });
        };
    }, []);
    const items = useMemo(()=>Array.from(itemsById.values()), [
        itemsById
    ]);
    const value = useMemo(()=>({
            items,
            register,
            editor: activeEditor,
            rootEditor
        }), [
        items,
        register,
        activeEditor,
        rootEditor
    ]);
    return /*#__PURE__*/ jsx(ToolbarExtensionsContext.Provider, {
        value: value,
        children: children
    });
}
function useToolbarExtensions() {
    const context = useContext(ToolbarExtensionsContext);
    if (null == context) throw new Error('useToolbarExtensions must be used within a ToolbarExtensionsProvider');
    return context;
}
export { ToolbarExtensionsProvider, useToolbarExtensions };
