"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = exports.Choice = void 0;
var _compat = require("preact/compat");
var _evEmitter = _interopRequireDefault(require("ev-emitter"));
var _classnames = _interopRequireDefault(require("classnames"));
var _useId = _interopRequireDefault(require("../utilities/useId"));
var _InlineError = require("../InlineError");
var _Label = require("../Label");
var _useLabelProps = require("../Label/useLabelProps");
var _useHint = require("../Hint/useHint");
var _cleanFieldProps = _interopRequireDefault(require("../utilities/cleanFieldProps"));
var _describeField = _interopRequireDefault(require("../utilities/describeField"));
var _jsxRuntime = require("preact/compat/jsx-runtime");
function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }
/** Used to emit events to all Choice components */
const dsChoiceEmitter = new _evEmitter.default();

/**
 * This component passes any additional props to its underlying input element
 * as attributes. See the corresponding MDN documentation for
 * [input](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input) for
 * a list of valid attributes.

 * For information about how and when to use this component, refer to the
 * [checkbox](https://design.cms.gov/components/checkbox/) and
 * [radio](https://design.cms.gov/components/radio/) documentation pages.
 */

const Choice = _ref => {
  let {
    _choiceChild,
    ...props
  } = _ref;
  const initialCheckedState = props.checked ?? props.defaultChecked;
  const [internalCheckedState, setChecked] = (0, _compat.useState)(initialCheckedState);
  const isControlled = props.checked !== undefined;
  const checked = isControlled ? props.checked : internalCheckedState;
  const radioCheckedEventName = `${props.name}-radio-checked`;
  const id = (0, _useId.default)('choice--', props.id);
  const {
    hintId,
    hintElement
  } = (0, _useHint.useHint)({
    ...props,
    id
  });
  const labelProps = (0, _useLabelProps.useLabelProps)({
    ...props,
    id
  });
  let errorId;
  let errorElement;
  if (!_choiceChild) {
    errorId = props.errorId ?? `${id}__error`;
    errorElement = /*#__PURE__*/(0, _jsxRuntime.jsx)(_InlineError.InlineError, {
      id: errorId,
      inversed: props.inversed,
      className: props.errorMessageClassName,
      children: props.errorMessage
    });
  }

  // Subscribe to changes from other radio buttons in the same group
  (0, _compat.useEffect)(() => {
    // This logic only applies to uncontrolled radio groups
    if (props.type !== 'radio' || isControlled) {
      return;
    }
    const handleRadioChecked = checkedId => {
      // A radio button in this group was just checked. If it wasn't this one, uncheck this one
      if (checkedId !== id) {
        setChecked(false);
      }
    };
    dsChoiceEmitter.on(radioCheckedEventName, handleRadioChecked);
    return () => {
      dsChoiceEmitter.off(radioCheckedEventName, handleRadioChecked);
    };
  }, [setChecked]);
  function handleChange(event) {
    if (props.onChange) {
      props.onChange(event);
    }
    if (!isControlled) {
      setChecked(event.target.checked);
      if (props.type === 'radio' && event.target.checked) {
        // Emit an event so other radio options can uncheck themselves
        dsChoiceEmitter.emitEvent(radioCheckedEventName, [id]);
      }
    }
  }
  const {
    'aria-live': ariaLive,
    'aria-relevant': ariaRelevant,
    'aria-atomic': ariaAtomic,
    className,
    inversed,
    inputClassName,
    inputRef,
    size,
    checkedChildren,
    uncheckedChildren,
    ...inputProps
  } = props;
  return /*#__PURE__*/(0, _jsxRuntime.jsxs)("div", {
    className: className,
    "aria-live": ariaLive ?? (checkedChildren ? 'polite' : null),
    "aria-relevant": ariaRelevant ?? (checkedChildren ? 'additions text' : null),
    "aria-atomic": ariaAtomic ?? (checkedChildren ? 'false' : null),
    children: [/*#__PURE__*/(0, _jsxRuntime.jsxs)("div", {
      className: "ds-c-choice-wrapper",
      children: [/*#__PURE__*/(0, _jsxRuntime.jsx)("input", {
        ...(0, _cleanFieldProps.default)(inputProps),
        id: id,
        className: (0, _classnames.default)(inputClassName, 'ds-c-choice', {
          'ds-c-choice--inverse': inversed,
          'ds-c-choice--small': size === 'small'
        }),
        onChange: handleChange,
        ref: inputRef,
        "aria-describedby": (0, _describeField.default)({
          ...props,
          errorId,
          hintId
        })
      }), /*#__PURE__*/(0, _jsxRuntime.jsx)(_Label.Label, {
        ...labelProps,
        fieldId: id
      }), hintElement, errorElement]
    }), checked ? checkedChildren : uncheckedChildren]
  });
};
exports.Choice = Choice;
Choice.defaultProps = {
  _choiceChild: false
};
var _default = exports.default = Choice;