import { useMemo, useEffect, useRef, useSyncExternalStore, useCallback } from "react";
import {
  mapValues
} from "@makeswift/controls";
import * as ReactPage from "../../../state/react-page";
import { useResourceResolver } from "./use-resource-resolver";
import { useDocumentKey } from "./use-document-context";
import { useSelector } from "./use-selector";
import { useStylesheetFactory } from "./use-stylesheet-factory";
import { useResolvableRecord } from "./use-resolvable-record";
import { propErrorHandlingProxy } from "../utils/prop-error-handling-proxy";
function useControlInstances(elementKey) {
  const documentKey = useDocumentKey();
  return useSelector((state) => {
    if (documentKey == null)
      return null;
    return ReactPage.getPropControllers(state, documentKey, elementKey);
  });
}
function useResolvedProps(propDefs, elementData, elementKey) {
  const stylesheetFactory = useStylesheetFactory();
  const resourceResolver = useResourceResolver();
  const controls = useControlInstances(elementKey);
  const cache = useRef({}).current;
  const resolveProp = useCallback(
    (def, propName) => {
      const data = elementData[propName];
      const control = controls?.[propName];
      if (cache[propName] != null && data === cache[propName].data && control === cache[propName].control) {
        return cache[propName].resolvedValue;
      }
      const resolvedValue = def.resolveValue(
        data,
        resourceResolver,
        stylesheetFactory.get(propName),
        control
      );
      cache[propName] = { data, control, resolvedValue };
      return resolvedValue;
    },
    [controls, elementData, resourceResolver, stylesheetFactory]
  );
  const resolvables = useMemo(
    () => mapValues(propDefs, (def, propName) => {
      const defaultValue = def.config?.defaultValue;
      return propErrorHandlingProxy(resolveProp(def, propName), defaultValue, (error) => {
        console.warn(
          `Error reading value for prop "${propName}", falling back to \`${defaultValue}\`.`,
          { control: def, error }
        );
      });
    }),
    [propDefs, resolveProp]
  );
  const props = useResolvableRecord(resolvables);
  useEffect(() => {
    props.triggerResolve();
  }, [props]);
  const resolvedProps = useSyncExternalStore(props.subscribe, props.readStable, props.readStable);
  stylesheetFactory.useDefinedStyles();
  return resolvedProps;
}
export {
  useResolvedProps
};
//# sourceMappingURL=use-resolved-props.js.map