/**
 * @license MIT
 * author: Cube Dev Team
 * @cube-dev/ui-kit v0.0.0-canary-5e810c3
 * Released under the MIT license.
 */

import { jsx as _jsx } from "react/jsx-runtime";
import { forwardRef, useCallback, useEffect, useState } from 'react';
import { filterBaseProps, tasty } from '../tasty/index.js';
import { useCombinedRefs } from '../utils/react/index.js';
const GridElement = tasty({
    styles: {
        display: 'contents',
    },
});
const COLUMN_WIDTH = '(($grid-width - ($column-gap * ($columns-amount - 1))) / $columns-amount)';
export const GridProvider = forwardRef(function GridProvider(props, outerRef) {
    let ref = useCombinedRefs(outerRef);
    let { children, columns = 2, gap = '0', width: forcedWidth, initialWidth, } = props;
    let [width, setWidth] = useState(forcedWidth || initialWidth || '100vw');
    const resizeCallback = useCallback(() => {
        const el = ref?.current?.parentElement;
        if (!el)
            return;
        const computedStyle = getComputedStyle(el);
        const containerWidth = el.clientWidth -
            parseFloat(computedStyle.paddingLeft) -
            parseFloat(computedStyle.paddingRight);
        setWidth(`${containerWidth}px`);
    }, [ref, columns, gap]);
    useEffect(() => {
        if (forcedWidth)
            return;
        const el = ref && ref.current && ref.current.parentNode;
        if (!el)
            return;
        let sensor;
        import('../utils/ResizeSensor.js')
            .then((module) => module.ResizeSensor)
            .then((ResizeSensor) => {
            sensor = new ResizeSensor(el, resizeCallback);
        });
        return () => {
            if (sensor) {
                sensor.detach();
            }
        };
    }, [resizeCallback]);
    useEffect(() => {
        if (forcedWidth)
            return;
        resizeCallback();
    }, [resizeCallback]);
    return (_jsx(GridElement, { ...filterBaseProps(props, { eventProps: true }), ref: ref, styles: {
            '--grid-width': width,
            '--columns-amount': columns,
            '--column-gap': gap,
            '--column-width': COLUMN_WIDTH,
        }, children: children }));
});

        