import { jsx as _jsx } from "react/jsx-runtime";
import { forwardRef, Children, cloneElement, useState, useEffect, useRef, useMemo } from 'react';
import styled, { css } from 'styled-components';
import FormField from '../FormField';
import { StyledFormField, StyledFormFieldInfo } from '../FormField/FormField';
import Flex from '../Flex';
import { defaultThemeProp } from '../../theme';
import { useArrows, useConsolidatedRef, useElement, useTestIds, useUID } from '../../hooks';
import { StyledImageContainer, StyledSelectionCard, StyledSelectionCardInline } from '../SelectionCard/SelectionCard.styles';
import { getActiveElement, withTestIds } from '../../utils';
import { StyledRadioCheck } from '../RadioCheck/RadioCheck';
import { getRadioCheckGroupTestIds } from './RadioCheckGroup.test-ids';
export const StyledRadioCheckGroup = styled.fieldset(() => {
    return css `
    container-type: inline-size;
    flex-wrap: nowrap;

    &[disabled] {
      > ${StyledFormField} {
        opacity: unset;
      }
    }

    ${StyledSelectionCard} {
      max-width: 100%;
    }

    ${StyledSelectionCardInline} ${StyledImageContainer} {
      /* To enlarge the image containers to the size of the biggest one */
      min-height: 100%;
    }

    ${StyledRadioCheck} > ${StyledFormFieldInfo} {
      display: none;
    }
  `;
});
const getCardGridColumns = (cardWidth) => css `
  @container (min-width: calc(2 * ${cardWidth})) {
    grid-template-columns: repeat(2, 1fr);
  }

  @container (min-width: calc(3 * ${cardWidth})) {
    grid-template-columns: repeat(3, 1fr);
  }

  @container (min-width: calc(4 * ${cardWidth})) {
    grid-template-columns: repeat(4, 1fr);
  }
`;
const getCardGridContainerStyles = (theme) => {
    const defaultCardWidth = theme.base['content-width'].sm;
    const inlineImageCardWidth = theme.base['content-width'].md;
    return css `
    display: grid;
    gap: ${theme.base.spacing};
    grid-template-columns: 1fr;
    grid-auto-rows: 1fr;

    ${getCardGridColumns(defaultCardWidth)}

    &:has(${StyledSelectionCardInline}) {
      ${getCardGridColumns(inlineImageCardWidth)}
    }
  `;
};
const StyledCardGrid = styled.div(({ theme, renderInline, autoStack, childCount }) => {
    if (!renderInline) {
        return css `
      display: grid;
      gap: ${theme.base.spacing};
      grid-template-columns: minmax(min-content, max-content);
      grid-auto-rows: 1fr;
    `;
    }
    return autoStack
        ? getCardGridContainerStyles(theme)
        : css `
        display: grid;
        gap: ${theme.base.spacing};
        grid-template-columns: repeat(${childCount}, 1fr);
        grid-auto-rows: 1fr;
      `;
});
StyledCardGrid.defaultProps = defaultThemeProp;
const RadioCheckGroup = forwardRef(function RadioCheckGroup(props, ref) {
    const uid = useUID();
    const { testId, children, name = uid, disabled = false, required = false, onChange, readOnly, inline = false, autoStack = true, variant = 'simple', arrowNavigation = true, onClear, ...restProps } = props;
    const testIds = useTestIds(testId, getRadioCheckGroupTestIds);
    const [optionsEl, setOptionsEl] = useElement();
    const [renderInline, setRenderInline] = useState(inline);
    const renderInlineRef = useRef(inline);
    const minInlineWidth = useRef(0);
    const containerRef = useConsolidatedRef(ref);
    const skipRef = useRef(null);
    useArrows(arrowNavigation ? containerRef : skipRef, {
        selector: '[data-main-focus]',
        cycle: false,
        dir: 'both'
    }, [children]);
    useEffect(() => {
        setRenderInline(inline);
        if (inline && optionsEl && optionsEl.lastChild && autoStack) {
            const intersectionObserver = new IntersectionObserver(entries => {
                if (entries[0].intersectionRatio < 1) {
                    if (entries[0].rootBounds)
                        minInlineWidth.current = entries[0].rootBounds.width + 1;
                    renderInlineRef.current = false;
                    setRenderInline(false);
                }
            }, { root: optionsEl, threshold: 1 });
            const resizeObserver = new ResizeObserver(entries => {
                if (!renderInlineRef.current && entries[0].contentRect.width > minInlineWidth.current) {
                    renderInlineRef.current = true;
                    setRenderInline(true);
                }
            });
            intersectionObserver.observe(optionsEl.lastChild);
            resizeObserver.observe(optionsEl);
            return () => {
                intersectionObserver.disconnect();
                resizeObserver.disconnect();
            };
        }
    }, [optionsEl, inline, autoStack]);
    const mapChildren = useMemo(() => Children.map(children, child => cloneElement(child, {
        name,
        status: restProps.status,
        disabled: disabled || child.props.disabled,
        readOnly: readOnly || child.props.readOnly,
        variant: variant === 'card-grid' ? 'card' : variant,
        suppressAnnouncements: true,
        onChange: onChange
            ? (e) => {
                if (!(readOnly || child.props.readOnly)) {
                    child.props.onChange?.(e);
                    onChange(e);
                }
            }
            : child.props.onChange
    })), [children, name, disabled, readOnly, variant, onChange]);
    return (_jsx(FormField, { testId: testIds, as: StyledRadioCheckGroup, ref: containerRef, name: name, disabled: disabled, required: required, ...restProps, inline: false, isRadioCheck: true, onClear: onClear, 
        // Prevents blur when any input within the group is actively focused.
        onMouseDown: (e) => {
            restProps.onMouseDown?.(e);
            if (!containerRef.current)
                return;
            if (!containerRef.current.contains(getActiveElement()))
                return;
            if (!(e.target instanceof Element) || !e.target.closest('label'))
                return;
            e.preventDefault();
        }, children: variant === 'card-grid' ? (_jsx(StyledCardGrid, { ref: setOptionsEl, renderInline: renderInline, autoStack: autoStack, childCount: Children.count(children), children: mapChildren })) : (_jsx(Flex, { ref: setOptionsEl, container: {
                direction: renderInline ? 'row' : 'column',
                colGap: renderInline ? 1.5 : 2,
                rowGap: variant === 'card' ? 1 : 0,
                wrap: 'wrap'
            }, children: mapChildren })) }));
});
export default withTestIds(RadioCheckGroup, getRadioCheckGroupTestIds);
//# sourceMappingURL=RadioCheckGroup.js.map