import { jsx as _jsx, Fragment as _Fragment, jsxs as _jsxs } from "react/jsx-runtime";
import { forwardRef, useEffect } from 'react';
import styled, { css } from 'styled-components';
import { hideVisually, mix } from 'polished';
import FormField, { StyledFormFieldInfo } from '../FormField';
import { StyledFormControl } from '../FormControl';
import { defaultThemeProp } from '../../theme';
import { getActiveElement, tryCatch } from '../../utils';
import { useConsolidatedRef, useDirection, useI18n, useUID } from '../../hooks';
import { StyledLabel } from '../Label';
import { calculateFontSize, readableColor } from '../../styles';
import VisuallyHiddenText from '../VisuallyHiddenText';
export const StyledPseudoRadioCheck = styled.div(props => {
    const { theme: { base: { spacing, palette: { 'primary-background': primaryBackground } }, components: { 'form-field': formField, 'radio-check': { size, 'touch-size': touchSize, 'background-color': backgroundColor, 'border-color': borderColor, 'border-width': borderWidth } } }, status } = props;
    const useBorderColor = status === 'error' ? formField.error['status-color'] : borderColor;
    const useBackgroundColor = status && formField[status]
        ? tryCatch(() => mix(0.8, primaryBackground, formField[status]['status-color']))
        : backgroundColor;
    return css `
      display: flex;
      flex-shrink: 0;
      position: relative;
      width: ${size};
      height: ${size};
      margin-inline-end: ${spacing};
      border: ${borderWidth} solid ${useBorderColor};
      background-color: ${useBackgroundColor};

      @media (pointer: coarse) {
        width: ${touchSize};
        height: ${touchSize};
      }

      &::after {
        content: '';
        display: none;
      }
    `;
});
StyledPseudoRadioCheck.defaultProps = defaultThemeProp;
export const StyledRadioCheckInput = styled.input(props => {
    const { disabled, theme: { base: { 'border-radius': baseBorderRadius }, components: { 'form-control': { ':focus': { 'box-shadow': shadow, 'border-color': focusBorderColor }, ':read-only': { 'background-color': readOnlyBackgroundColor } }, 'radio-check': { size, ':checked': { 'background-color': checkedBackgroundColor, 'border-color': checkedBorderColor } }, checkbox: { 'border-radius': checkRadius }, 'radio-button': { 'border-radius': radioRadius } } } } = props;
    const backgroundColor = props.readOnly ? readOnlyBackgroundColor : checkedBackgroundColor;
    const foreground = tryCatch(() => readableColor(backgroundColor));
    const prcSelector = `+ ${StyledLabel} ${StyledPseudoRadioCheck}`;
    const { ltr } = useDirection();
    return css `
    ${hideVisually}
    margin: 0;

    /* Sets rect size for JAWS focus outline */
    width: ${size};
    height: ${size};

    ${!disabled &&
        css `
      &:focus ${prcSelector} {
        box-shadow: ${shadow};
        border-color: ${focusBorderColor};
      }
    `}

    &:checked
      ${prcSelector},
      &:checked:disabled
      ${prcSelector},
      &[type='checkbox']:indeterminate
      ${prcSelector},
      &[type='checkbox']:indeterminate:disabled
      ${prcSelector} {
      border-color: ${props.readOnly ? 'inherit' : checkedBorderColor};
      background-color: ${backgroundColor};

      &::after {
        display: block;
      }
    }

    &[type='radio'] ${prcSelector}, &[type='radio'] ${prcSelector}::after {
      border-radius: ${radioRadius};
    }

    &[type='radio'] ${prcSelector}::after {
      margin: auto;
      width: 100%;
      height: 100%;
      background-color: ${foreground};
      transform: scale(0.4);
    }

    &[type='checkbox'] ${prcSelector} {
      border-radius: min(calc(${baseBorderRadius} * ${checkRadius}), 0.25rem);
    }

    &[type='checkbox']:not(:indeterminate) ${prcSelector} {
      &::after {
        width: 40%;
        height: 75%;
        ${ltr
        ? css `
              transform: rotate(45deg) translate(50%, -30%);
            `
        : css `
              transform: rotate(45deg) translate(-50%, 30%);
            `}
        border-right: 0.15em solid ${foreground};
        border-bottom: 0.15em solid ${foreground};
      }
    }

    &[type='checkbox']:indeterminate ${prcSelector} {
      display: flex;
      &::after {
        width: 90%;
        height: 0.15em;
        margin: auto;
        background-color: ${foreground};
      }
    }
  `;
});
StyledRadioCheckInput.defaultProps = defaultThemeProp;
export const StyledRadioCheck = styled.div(props => {
    const { disabled, readOnly, theme: { base, components: { 'radio-check': { label: { color: labelColor, 'font-weight': labelFontWeight } }, 'form-control': { ':hover': { 'border-color': hoverBorderColor } } } } } = props;
    const fontSize = calculateFontSize(base['font-size'], base['font-scale']);
    return css `
      > ${StyledLabel} {
        cursor: pointer;
        display: flex;
        align-items: center;
        font-weight: ${labelFontWeight};
        word-break: break-word;
        font-size: ${fontSize.s};
        color: ${labelColor};
        margin: 0;
        min-height: ${base['hit-area']['mouse-min']};

        @media (pointer: coarse) {
          min-height: ${base['hit-area']['finger-min']};
        }
      }

      > ${StyledFormFieldInfo} {
        margin: 0;
        padding-inline-start: calc(${base.spacing} / 4);
      }

      ${!(disabled || readOnly) &&
        css `
        &:not(:focus-within) > ${StyledLabel}:hover ${StyledPseudoRadioCheck} {
          border-color: ${hoverBorderColor};
        }
      `}
    `;
});
StyledRadioCheck.defaultProps = defaultThemeProp;
export const StyledRadioCheckCard = styled.label(({ disabled, readOnly, status, theme: { base: { palette, shadow, spacing }, components: { card, 'form-field': formField, 'radio-check': { label }, 'form-control': { ':hover': { 'border-color': hoverBorderColor } } } } }) => {
    const useBorderColor = status === 'error' ? formField.error['status-color'] : palette['border-line'];
    return css `
      min-width: min-content;
      cursor: pointer;
      background-color: ${card.background};
      border-radius: ${card['border-radius']};
      border: 0.0625rem solid ${useBorderColor};
      padding: ${spacing};

      ${disabled &&
        css `
        cursor: not-allowed;
      `}

      ${!(disabled || readOnly) &&
        css `
        :hover:not(:focus-within) {
          border-color: ${hoverBorderColor};
          ${StyledLabel} ${StyledPseudoRadioCheck} {
            border-color: ${hoverBorderColor};
          }
        }

        :focus-within {
          box-shadow: ${shadow.focus};
          border-color: transparent;
        }
      `}

    > ${StyledLabel} {
        display: flex;
        align-items: center;
        color: ${label.color};
        font-weight: ${label['font-weight']};
        margin: 0;
      }

      > ${StyledFormFieldInfo} {
        margin: 0;
        padding-inline-start: calc(${spacing} / 4);
      }
    `;
});
StyledRadioCheckCard.defaultProps = defaultThemeProp;
export default forwardRef(function RadioCheck(props, ref) {
    const uid = useUID();
    const t = useI18n();
    const { type, id = uid, label, required = false, disabled = false, indeterminate = false, readOnly = false, variant = 'simple', onClick, onKeyDown, status, info, additionalInfo, ...restProps } = props;
    const isRadio = type === 'radio';
    const card = variant === 'card';
    const inputRef = useConsolidatedRef(ref);
    useEffect(() => {
        if (!isRadio && inputRef.current)
            inputRef.current.indeterminate = !!indeterminate;
    }, [inputRef, indeterminate, isRadio]);
    // Prevents blur when a user mouse clicks the label to select an input that is actively focused.
    useEffect(() => {
        if (!inputRef.current)
            return;
        const labelEl = inputRef.current.nextSibling;
        if (labelEl?.nodeName.toUpperCase() !== 'LABEL')
            return;
        const ac = new AbortController();
        labelEl.addEventListener('mousedown', e => {
            if (inputRef.current === getActiveElement()) {
                e.preventDefault();
            }
        }, { signal: ac.signal });
        return () => {
            ac.abort();
        };
    }, []);
    return (_jsx(FormField, { as: card ? StyledRadioCheckCard : StyledRadioCheck, label: _jsxs(_Fragment, { children: [_jsx(StyledPseudoRadioCheck, { status: status, isRadio: isRadio, as: StyledFormControl, required: required, disabled: disabled, readOnly: readOnly }), _jsxs(_Fragment, { children: [label, readOnly && _jsx(VisuallyHiddenText, { children: ` ${t('read_only')}` })] })] }), labelAs: card ? 'div' : undefined, id: id, required: required, disabled: disabled, readOnly: readOnly, status: status, info: info, isRadioCheck: true, inline: true, labelAfter: true, additionalInfo: additionalInfo, children: _jsx(StyledRadioCheckInput, { ...restProps, id: id, type: type, required: required, disabled: disabled, readOnly: readOnly, onClick: (e) => {
                if (readOnly)
                    e.preventDefault();
                onClick?.(e);
            }, onKeyDown: (e) => {
                if (type === 'checkbox' && readOnly && e.key === ' ') {
                    e.preventDefault();
                }
                if (type === 'radio' && readOnly && e.key.includes('Arrow')) {
                    e.preventDefault();
                }
                onKeyDown?.(e);
            }, ref: inputRef }) }));
});
//# sourceMappingURL=RadioCheck.js.map