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 { useArrows, useConsolidatedRef, useElement, useTestIds, useTheme, useUID } from '../../hooks';
import Grid from '../Grid';
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 `
    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 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', onClear, ...restProps } = props;
    const testIds = useTestIds(testId, getRadioCheckGroupTestIds);
    const theme = useTheme();
    const [optionsEl, setOptionsEl] = useElement();
    const [renderInline, setRenderInline] = useState(inline);
    const renderInlineRef = useRef(inline);
    const minInlineWidth = useRef(0);
    const containerRef = useConsolidatedRef(ref);
    useArrows(containerRef, {
        selector: '[data-main-focus]',
        cycle: false,
        dir: 'left-right'
    });
    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, 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(Grid, { container: {
                gap: 1,
                cols: (() => {
                    if (!renderInline)
                        return 'minmax(min-content, max-content)';
                    if (autoStack)
                        return `repeat(auto-fit, minmax(min(100%, ${theme.base['content-width'].sm}), 1fr))`;
                    return `repeat(${Children.count(children)}, 1fr)`;
                })(),
                autoRows: '1fr'
            }, 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