import { jsx } from "react/jsx-runtime";
import { createContext, useCallback, useContext, useEffect, useState } from "react";
import { autoUpdate, offset, safePolygon, shift, useDismiss, useFloating, useHover, useInteractions } from "@floating-ui/react";
import { useDesignable } from "../../hooks/index.mjs";
import BlockToolbar from "./BlockToolbar.mjs";
const ToolbarContext = /*#__PURE__*/ createContext({});
const ToolbarProvider = (param)=>{
    let { children, onVisibilityChange } = param;
    const [childStates, setChildStates] = useState({});
    const registerChild = useCallback((id, isVisible)=>{
        setChildStates((prev)=>({
                ...prev,
                [id]: isVisible
            }));
        return ()=>{
            setChildStates((prev)=>{
                const newState = {
                    ...prev
                };
                delete newState[id];
                return newState;
            });
        };
    }, []);
    const isVisible = Object.values(childStates).some((visible)=>visible);
    useEffect(()=>{
        if (onVisibilityChange) onVisibilityChange(!isVisible);
    }, [
        isVisible,
        onVisibilityChange
    ]);
    return /*#__PURE__*/ jsx(ToolbarContext.Provider, {
        value: {
            registerChild
        },
        children: children
    });
};
const useToolbar = ()=>useContext(ToolbarContext);
const useBlockToolbar = ()=>{
    const [open, setOpen] = useState(false);
    const { designable } = useDesignable();
    const { refs, floatingStyles, context } = useFloating({
        placement: 'top',
        middleware: [
            offset(10),
            shift({
                crossAxis: true,
                padding: 10
            })
        ],
        open,
        onOpenChange: setOpen,
        whileElementsMounted: autoUpdate
    });
    const { getReferenceProps, getFloatingProps } = useInteractions([
        useHover(context, {
            handleClose: safePolygon(),
            delay: {
                open: 0,
                close: 100
            }
        }),
        useDismiss(context)
    ]);
    const toolbar = open && designable && /*#__PURE__*/ jsx(BlockToolbar, {
        ref: refs.setFloating,
        style: {
            ...floatingStyles,
            zIndex: 9999
        },
        ...getFloatingProps()
    });
    return {
        open,
        ref: refs.setReference,
        props: getReferenceProps(),
        toolbar
    };
};
export { ToolbarContext, ToolbarProvider, useBlockToolbar, useToolbar };
