"use strict";
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
const jsxRuntime = require("react/jsx-runtime");
const reactBinding = require("@contember/react-binding");
const reactUtils = require("@contember/react-utils");
const ui = require("@contember/ui");
const react = require("react");
const renderByJoining = require("./renderByJoining.cjs");
const RoutingLink = require("../../../../routing/RoutingLink.cjs");
const reactRouting = require("@contember/react-routing");
function DimensionsRenderer(props) {
  const environment = reactBinding.useEnvironment();
  const redirect = reactRouting.useRedirect();
  const renderSelected = react.useCallback((selectedDimensions2) => {
    const renderer = props.renderSelected || renderByJoining.renderByJoining;
    return renderer(selectedDimensions2);
  }, [props.renderSelected]);
  const renderContent = (dimensionData, selectedDimensions2) => {
    const canSelectJustOne = props.minItems === 1 && props.maxItems === 1;
    const selectedDimensionsCount = selectedDimensions2.length;
    const canSelectAnother = selectedDimensionsCount < props.maxItems;
    const canSelectLess = selectedDimensionsCount > props.minItems;
    const getRequestChangeCallback = (dimension) => (reqState) => {
      if (reqState === null) {
        throw "Cannot switch dimension of unmatched request";
      }
      let updatedDimensions;
      if (!dimension.isSelected && !canSelectAnother) {
        updatedDimensions = [...selectedDimensions2.slice(1), dimension];
      } else if (dimension.isSelected && !canSelectLess) {
        updatedDimensions = selectedDimensions2;
      } else {
        updatedDimensions = dimensionData.filter((item) => {
          if (item.slug === dimension.slug) {
            return !item.isSelected;
          }
          return item.isSelected;
        });
      }
      return {
        ...reqState,
        dimensions: {
          ...reqState.dimensions || {},
          [props.dimension]: getUniqueDimensions(updatedDimensions.map((item) => item.slug).slice(0, props.maxItems))
        }
      };
    };
    const renderedDimensions = dimensionData.map((dimension) => {
      if (canSelectJustOne) {
        return /* @__PURE__ */ jsxRuntime.jsx(
          RoutingLink.RoutingLink,
          {
            to: getRequestChangeCallback(dimension),
            Component: ({ href, onClick }) => /* @__PURE__ */ jsxRuntime.jsx(
              ui.AnchorButton,
              {
                href,
                display: "block",
                active: dimension.isSelected,
                onClick,
                children: dimension.label
              }
            )
          },
          dimension.slug
        );
      } else {
        return /* @__PURE__ */ jsxRuntime.jsx(
          ui.FieldContainer,
          {
            display: "inline",
            label: dimension.label,
            labelPosition: "right",
            children: /* @__PURE__ */ jsxRuntime.jsx(
              ui.Checkbox,
              {
                value: dimension.isSelected,
                disabled: dimension.isSelected && !canSelectLess,
                onChange: () => redirect(getRequestChangeCallback(dimension))
              },
              dimension.slug
            )
          },
          dimension.slug
        );
      }
    });
    if (canSelectJustOne) {
      return /* @__PURE__ */ jsxRuntime.jsx(ui.ButtonGroup, { direction: "vertical", display: "block", inset: "border", children: renderedDimensions });
    }
    return /* @__PURE__ */ jsxRuntime.jsx(ui.Box, { border: false, gap: "gutter", padding: "gutter", children: renderedDimensions }, "multipleDimensions");
  };
  const getNormalizedData = (currentDimensions, accessor) => {
    const entities = Array.from(accessor);
    const normalized = [];
    for (const entity of entities) {
      if (!(entity instanceof reactBinding.EntityAccessor)) {
        continue;
      }
      const slugField = entity.getField(props.slugField);
      if (typeof slugField.value === "string") {
        const slugValue = slugField.value;
        normalized.push({
          slug: slugValue,
          isSelected: currentDimensions.indexOf(slugValue) !== -1,
          label: /* @__PURE__ */ jsxRuntime.jsx(reactBinding.Entity, { accessor: entity, children: props.labelFactory })
        });
      }
    }
    return normalized;
  };
  const getUniqueDimensions = (selectedDimensions2) => {
    return selectedDimensions2.filter((item, i, array) => array.indexOf(item) === i);
  };
  const uniqueDimensions = getUniqueDimensions(environment.getDimensionOrElse(props.dimension, []));
  const normalizedData = getNormalizedData(uniqueDimensions, props.accessor);
  const selectedDimensions = normalizedData ? uniqueDimensions.filter((slug) => normalizedData.find((item) => item.slug === slug) !== void 0).map((dimension) => normalizedData.find((item) => item.slug === dimension)).filter((item) => !!item && item.isSelected) : reactUtils.emptyArray;
  react.useEffect(() => {
    const redirectTarget = selectedDimensions.length === 0 ? normalizedData || [] : selectedDimensions;
    if (normalizedData !== void 0 && selectedDimensions.length === 0 && redirectTarget.length > 0) {
      redirect((requestState) => {
        return {
          ...requestState,
          dimensions: {
            ...requestState?.dimensions ?? {},
            [props.dimension]: getUniqueDimensions(redirectTarget.map((item) => item.slug).slice(0, props.maxItems))
          }
        };
      });
    }
  }, [normalizedData, props.dimension, props.maxItems, redirect, selectedDimensions]);
  const buttonProps = react.useMemo(() => ({
    distinction: "seamless",
    size: "small",
    ...props.buttonProps,
    children: renderSelected(selectedDimensions)
  }), [props.buttonProps, renderSelected, selectedDimensions]);
  if (normalizedData.length === 0) {
    return null;
  }
  if (normalizedData.length === 1) {
    return /* @__PURE__ */ jsxRuntime.jsx("div", { className: "dimensionsSwitcher", children: /* @__PURE__ */ jsxRuntime.jsx("div", { className: "dimensionsSwitcher-staticSelected", children: renderSelected(selectedDimensions) }) });
  }
  return /* @__PURE__ */ jsxRuntime.jsx(ui.Dropdown, { buttonProps, children: renderContent(normalizedData, selectedDimensions) });
}
exports.DimensionsRenderer = DimensionsRenderer;
//# sourceMappingURL=DimensionsRenderer.cjs.map
