import { jsx, jsxs, Fragment } from "react/jsx-runtime";
import { BindingError, useEnvironment, QueryLanguage, Field, DataBindingProvider, EntityListSubTree } from "@contember/react-binding";
import { Spinner } from "@contember/ui";
import { memo, useMemo } from "react";
import { DimensionsRenderer } from "./DimensionsRenderer.js";
const DimensionsStateRenderer = (props) => {
  if (props.accessorTreeState.name === "initialized") {
    return /* @__PURE__ */ jsx(Fragment, { children: props.children });
  }
  return /* @__PURE__ */ jsx(Spinner, {});
};
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__ */ jsx(Field, { field: props.labelField });
  return /* @__PURE__ */ jsx(DataBindingProvider, { stateComponent: DimensionsStateRenderer, children: /* @__PURE__ */ jsxs(
    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
      },
      children: [
        labelFactory,
        /* @__PURE__ */ jsx(Field, { field: props.slugField })
      ]
    }
  ) }, key);
});
DimensionsSwitcher.displayName = "DimensionsSwitcher";
export {
  DimensionsSwitcher
};
//# sourceMappingURL=DimensionsSwitcher.js.map
