import * as React from 'react';
import { useRef } from 'react';
import { useResizeObserver } from '../ResizeObserver';
const WRAPPER_STYLE = {
    position: 'absolute',
    pointerEvents: 'none',
    width: 0,
    height: 0,
    lineHeight: 0,
    fontSize: 0,
    overflow: 'hidden',
};
export const useCSSVariableWatch = (params) => {
    const lastValueRef = useRef(0);
    const onResize = React.useCallback(({ height }) => {
        if (height != null && height !== lastValueRef.current) {
            lastValueRef.current = height;
            params.onChange(height);
        }
    }, [params.onChange]);
    useResizeObserver(params.ref, onResize, { earlyAttach: true });
    React.useLayoutEffect(() => {
        const value = params.ref.current.getBoundingClientRect().height;
        if (value != null) {
            lastValueRef.current = value;
            return params.onChange(value);
        }
        else {
            console.warn(`Specified variable ${params.varName} not found or does not have a numeric value.`);
        }
    }, []);
};
export const CSSNumericVariableWatch = (props) => {
    const domRef = useRef(null);
    useCSSVariableWatch({
        ...props,
        ref: domRef,
    });
    const height = props.varName.startsWith('var(') ? props.varName : `var(${props.varName})`;
    const { allowInts = false } = props;
    return (React.createElement("div", { "data-name": "css-variable-watcher", "data-var": props.varName, style: WRAPPER_STYLE },
        React.createElement("div", { ref: domRef, style: {
                height: allowInts ? `calc(1px * ${height})` : height, // we do multiplication in order to support integer (without px) values as well
            } })));
};
