import {
  Checkbox
} from "./chunk-2VEO5SSY.js";
import {
  ErrorMessage
} from "./chunk-MZJT3USG.js";
import {
  Label
} from "./chunk-ZN7OWLZY.js";
import {
  useValidationClasses
} from "./chunk-DYOFXXZD.js";
import {
  spaceDelimitedList
} from "./chunk-DTWRSP5P.js";

// src/components/Checkbox/CheckboxGroup.tsx
import classNames from "classnames/dedupe";
import {
  Children,
  cloneElement,
  isValidElement,
  useEffect,
  useId,
  useRef,
  useState
} from "react";
import "@simplybusiness/mobius/src/components/Checkbox/CheckboxGroup.css";
import { jsx, jsxs } from "react/jsx-runtime";
var CheckboxGroup = ({ ref, ...props }) => {
  const {
    label,
    isDisabled = false,
    isRequired,
    isInvalid,
    orientation = "vertical",
    onChange,
    className,
    errorMessage,
    children,
    defaultValue = [],
    isReadOnly,
    itemsPerRow,
    lastItemDisables = false,
    ...rest
  } = props;
  const [selected, setSelected] = useState(defaultValue);
  const isInitializedRef = useRef(false);
  const prevDefaultValueRef = useRef(defaultValue);
  useEffect(() => {
    const hasChanged = defaultValue.length !== prevDefaultValueRef.current.length || defaultValue.some(
      (val, index) => val !== prevDefaultValueRef.current[index]
    );
    if (hasChanged || !isInitializedRef.current) {
      setSelected(defaultValue);
      prevDefaultValueRef.current = defaultValue;
      isInitializedRef.current = true;
    }
  }, [defaultValue]);
  const checkboxGroupClasses = classNames(
    "mobius",
    "mobius-checkbox-group",
    className,
    {
      "--is-horizontal": orientation === "horizontal",
      "--is-vertical": orientation === "vertical",
      "--is-required": typeof isRequired === "boolean" && isRequired,
      "--is-optional": typeof isRequired === "boolean" && !isRequired
    }
  );
  const validationClasses = useValidationClasses({ isInvalid });
  const labelClasses = classNames(
    {
      "--is-disabled": isDisabled
    },
    validationClasses
  );
  const errorMessageId = useId();
  const shouldErrorMessageShow = errorMessage ? errorMessageId : void 0;
  const describedBy = spaceDelimitedList([
    shouldErrorMessageShow,
    props["aria-describedby"]
  ]);
  const labelId = useId();
  const handleChange = (event, isLastItem = false) => {
    const {
      target: { value, checked }
    } = event;
    let newValue = [...selected];
    if (!checked) {
      newValue = selected.filter((item) => item !== value);
    }
    if (checked) {
      newValue = [...selected, value];
    }
    if (checked && lastItemDisables && isLastItem) {
      newValue = [value];
    }
    setSelected(newValue);
    onChange?.(newValue);
  };
  const childrenArray = Children.toArray(children);
  const lastCheckbox = childrenArray.filter(
    (child) => isValidElement(child) && child.type === Checkbox
  ).pop();
  const lastCheckboxIsChecked = lastCheckbox && selected.includes(lastCheckbox.props.value);
  return /* @__PURE__ */ jsxs(
    "div",
    {
      ...rest,
      "aria-labelledby": props["aria-labelledby"] || labelId,
      ref,
      className: checkboxGroupClasses,
      role: "group",
      style: {
        "--checkbox-items-per-row": itemsPerRow || Children.count(children)
      },
      children: [
        label && /* @__PURE__ */ jsx(Label, { elementType: "span", id: labelId, className: labelClasses, children: label }),
        /* @__PURE__ */ jsx("div", { className: "mobius-checkbox-group__wrapper", children: childrenArray.map((child) => {
          if (isValidElement(child)) {
            const isLastItem = child === lastCheckbox;
            const isChildDisabled = isDisabled || lastItemDisables && lastCheckboxIsChecked && !isLastItem;
            const childProps = child.props;
            return cloneElement(
              child,
              {
                isDisabled: isChildDisabled,
                isRequired,
                isReadOnly,
                isInvalid,
                isLastItem,
                selected: selected.includes(childProps.value),
                onChange: childProps.onChange || handleChange,
                "aria-describedby": describedBy
              }
            );
          }
          return child;
        }) }),
        errorMessage && /* @__PURE__ */ jsx(ErrorMessage, { id: errorMessageId, errorMessage })
      ]
    }
  );
};
CheckboxGroup.displayName = "CheckboxGroup";

export {
  CheckboxGroup
};
//# sourceMappingURL=chunk-576SEJGC.js.map
