import { getCSSPropRawValue, } from '@graphprotocol/gds-css';
import { useCSSProps } from "./useCSSProps.js";
import { useFirstRender } from "./useFirstRender.js";
export function useCSSPropsPolyfill(component, passedValues, options) {
    const { ref, returnPropValues } = options ?? {};
    const polyfillEnabled = !getStyleQueriesSupported();
    // Merge `passedValues` with `returnPropValues` if needed
    const allPassedValues = (() => {
        if (!returnPropValues)
            return passedValues;
        if (returnPropValues === true)
            return passedValues;
        const passed = passedValues;
        const merged = { ...passed };
        for (const key of Object.keys(returnPropValues)) {
            const value = returnPropValues[key];
            if (key in passedValues && passed[key] !== value) {
                throw new Error(`[useCSSPropsPolyfill] Conflicting values for prop \`${key}\`: ${String(passed[key])} vs ${value}`);
            }
            merged[key] = value;
        }
        return merged;
    })();
    const [callbackRef, propValues, cssProps] = useCSSProps(component, allPassedValues, {
        ref,
        disabled: !polyfillEnabled && !returnPropValues,
    });
    /**
     * Always include the polyfill attributes on the first render (even if the polyfill is disabled)
     * to prevent hydration errors. It would be nice to optimize for the case where the polyfill is
     * not needed instead (by always excluding the attributes on the first render, thereby not having
     * to immediately rerender in browsers that support style queries); unfortunately, that would
     * cause a flash of missing styles in browsers that need the polyfill.
     */
    const firstRender = useFirstRender({ immediatelyRerender: !polyfillEnabled });
    const polyfillAttributes = polyfillEnabled || firstRender
        ? Object.fromEntries(cssProps
            .filter((prop) => prop.name in passedValues)
            .map((prop) => {
            const value = propValues[prop.name];
            const rawValue = getCSSPropRawValue(prop, value);
            return [prop.polyfillAttribute, rawValue];
        }))
        : {};
    if (!returnPropValues) {
        return [callbackRef, polyfillAttributes];
    }
    const returnedPropValues = (returnPropValues === true
        ? propValues
        : Object.fromEntries(Object.entries(propValues).filter(([key]) => key in returnPropValues)));
    return [callbackRef, polyfillAttributes, returnedPropValues];
}
let privateStyleQueriesSupported = null;
function getStyleQueriesSupported() {
    if (typeof window === 'undefined' || typeof document === 'undefined')
        return false;
    if (privateStyleQueriesSupported === null) {
        privateStyleQueriesSupported =
            window.getComputedStyle(document.body).getPropertyValue('--gds-style-queries-test') ===
                'success';
    }
    return privateStyleQueriesSupported;
}
//# sourceMappingURL=useCSSPropsPolyfill.js.map