import { memo, useMemo, createElement, Fragment } from "react";
import { BindingError, useEnvironment, QueryLanguage, Field, DataBindingProvider, EntityListSubTree } from "@contember/binding";
import { Spinner } from "@contember/ui";
import { DimensionsRenderer } from "./DimensionsRenderer.js";
const DimensionsStateRenderer = (props) => {
  if (props.accessorTreeState.name === "initialized") {
    return /* @__PURE__ */ createElement(Fragment, null, props.children);
  }
  return /* @__PURE__ */ createElement(Spinner, null);
};
const DimensionsSwitcher = memo((props) => {
  const minItems = props.minItems === void 0 ? 1 : props.minItems;
  const maxItems = props.maxItems === void 0 ? 2 : props.maxItems;
  if (minItems > maxItems) {
    throw new BindingError(`DimensionSwitcher: 'minItems' for dimension ${props.dimension} must be no greater than 'maxItems'.`);
  }
  if (minItems < 1) {
    throw new BindingError(`DimensionSwitcher: 'minItems' for dimension ${props.dimension} must be at least 1.`);
  }
  const environment = useEnvironment();
  const qualifiedEntityList = QueryLanguage.desugarQualifiedEntityList({
    orderBy: props.orderBy,
    entities: props.optionEntities
  }, environment);
  const key = useMemo(() => JSON.stringify(qualifiedEntityList), [qualifiedEntityList]);
  const labelFactory = /* @__PURE__ */ createElement(Field, {
    field: props.labelField
  });
  return /* @__PURE__ */ createElement(DataBindingProvider, {
    stateComponent: DimensionsStateRenderer,
    refreshOnEnvironmentChange: false,
    key
  }, /* @__PURE__ */ createElement(EntityListSubTree, {
    entities: qualifiedEntityList,
    orderBy: qualifiedEntityList.orderBy,
    offset: qualifiedEntityList.offset,
    limit: qualifiedEntityList.limit,
    listComponent: DimensionsRenderer,
    listProps: {
      buttonProps: props.buttonProps,
      dimension: props.dimension,
      labelFactory,
      minItems,
      maxItems,
      renderSelected: props.renderSelected,
      slugField: props.slugField
    }
  }, labelFactory, /* @__PURE__ */ createElement(Field, {
    field: props.slugField
  })));
});
DimensionsSwitcher.displayName = "DimensionsSwitcher";
export { DimensionsSwitcher };
//# sourceMappingURL=DimensionsSwitcher.js.map
