import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import { useContext } from 'react';
import clsx from 'clsx';
import { isDef, addUnit } from '../utils';
import { isNumeric } from '../utils/validate/number';
import ConfigProviderContext from '../config-provider/ConfigProviderContext';

const Badge = props => {
  const {
    content,
    max,
    dot,
    showZero,
    tag = 'div'
  } = props;
  const {
    prefixCls,
    createNamespace
  } = useContext(ConfigProviderContext);
  const [bem] = createNamespace('badge', prefixCls);
  const TagElement = tag;

  const hasContent = () => {
    if (props.content) {
      return true;
    }

    return isDef(content) && content !== '' && (showZero || +content !== 0);
  };

  const renderContent = () => {
    if (!dot && hasContent()) {
      if (isDef(max) && isNumeric(content === null || content === void 0 ? void 0 : content.toString()) && +content > max) {
        return `${max}+`;
      }

      return content;
    }

    return null;
  };

  const renderBadge = () => {
    if (hasContent() || props.dot) {
      let style = {
        background: props.color
      };

      if (props.offset) {
        const [x, y] = props.offset;

        if (props.children) {
          style.top = addUnit(y);
          style.right = addUnit(x);
        } else {
          style.marginTop = addUnit(y);
          style.marginLeft = addUnit(x);
        }
      }

      if (!props.children) {
        style = Object.assign(Object.assign({}, props.style), style);
      }

      return _jsx("div", Object.assign({
        className: clsx({
          [props.className]: props.className && !props.children
        }, bem({
          dot: props.dot,
          fixed: !!props.children
        })),
        style: style
      }, {
        children: renderContent()
      }));
    }

    return null;
  };

  if (props.children) {
    return _jsxs(TagElement, Object.assign({
      className: clsx(bem('wrapper'), props.className),
      style: props.style,
      onClick: props.onClick,
      onTouchStart: props.onTouchStart
    }, {
      children: [props.children, renderBadge()]
    }));
  }

  return renderBadge();
};

Badge.defaultProps = {
  tag: 'div',
  showZero: true
};
export default Badge;