import { jsx as _jsx } from "@emotion/react/jsx-runtime";
import memoize from "fast-memoize";
import React from "react";
import { regex as formatRegex } from "./utils/format";
export const VariablesContext = React.createContext({
    variables: [],
    values: {},
    componentRef: undefined,
});
export const useVariablesContext = () => React.useContext(VariablesContext);
export const useVariableValues = () => useVariablesContext().values;
export const getVariableValue = memoize(function getVariableValue(variable, values) {
    const variableId = variable.replace(formatRegex, function (_, display, id) {
        return id;
    });
    const result = values[variableId];
    return typeof result !== "undefined" && result !== null ? result : "";
});
export function useVariable(variable) {
    const { values } = useVariablesContext();
    return getVariableValue(variable, values);
}
export const VariablesProvider = (props) => {
    const existing = useVariablesContext();
    const variables = React.useMemo(() => {
        var _a;
        return [...existing.variables, ...((_a = props.variables) !== null && _a !== void 0 ? _a : [])].filter((variable) => !(props.deletes || []).includes(variable.display));
    }, [props.variables, existing.variables, props.deletes]);
    const values = React.useMemo(() => {
        const variable = Object.assign(Object.assign({}, existing.values), (props.values || {}));
        return Object.fromEntries(Object.entries(variable).filter(
        // eslint-disable-next-line @typescript-eslint/no-unused-vars
        ([key, val]) => !(props.deletes || []).includes(key)));
    }, [props.values, existing.values, props.deletes]);
    const componentRef = React.useMemo(() => {
        return props.divElement
            ? { divElement: props.divElement }
            : existing.componentRef;
    }, [props.divElement, existing.componentRef]);
    const value = React.useMemo(() => ({
        variables,
        values,
        componentRef,
    }), [variables, values, componentRef]);
    return (_jsx(VariablesContext.Provider, Object.assign({ value: value }, { children: props.children })));
};
//# sourceMappingURL=VariablesContext.js.map