"use client";
import { cssStateVariables } from "./cssStates.js";
import { useStyle } from "../hooks/useStyle.js";
import { useRefWithInit } from "../hooks/useRefWithInit.js";
import { objectKeys } from "../../utils/objectKeys.js";
import { objectFromEntries } from "../../utils/objectFromEntries.js";
const cssStateVariableNames = objectKeys(cssStateVariables);
function useCSSState(options = {}, onChange) {
  const variables = useRefWithInit(
    () => cssStateVariableNames.flatMap((variableName) => {
      if (variableName === "open" && !("open" in options) || variableName === "blank" && !("blank" in options) || variableName === "checked" && !("checked" in options) || variableName === "disabled" && !("disabled" in options)) {
        return [];
      }
      const jsValue = (() => {
        switch (variableName) {
          case "open":
            return options.open;
          case "blank":
            return options.blank;
          case "checked":
            return options.checked;
          case "disabled":
            return options.disabled;
        }
      })();
      return [
        {
          name: variableName,
          initialValue: jsValue ?? cssStateVariables[variableName].defaultValue,
          cssProperty: `--gds-state-${variableName}`,
          dataAttribute: `data-gds-state-${variableName}`
        }
      ];
    })
  ).current;
  const cssProperties = useRefWithInit(() => variables.map((variable) => variable.cssProperty)).current;
  const initialValues = useRefWithInit(
    () => objectFromEntries(variables.map((variable) => [variable.cssProperty, String(variable.initialValue)]))
  );
  const getState = (values2) => {
    const state2 = objectFromEntries(
      variables.map((variable) => {
        const value = values2.get(variable.cssProperty) ?? variable.initialValue;
        return [variable.name, value === "true" ? true : value === "false" ? false : value];
      })
    );
    return state2;
  };
  const [callbackRef, values] = useStyle(cssProperties, {
    ref: options.ref,
    initialValues: initialValues.current,
    onChange: onChange ? (values2) => {
      onChange(getState(values2));
    } : void 0
  });
  const state = getState(values);
  const forwardedAttributes = objectFromEntries(
    variables.map((variable) => [variable.dataAttribute, String(state[variable.name])])
  );
  return [callbackRef, { ...state, forwardedAttributes }];
}
export {
  useCSSState
};
