import { jsx as _jsx } from "react/jsx-runtime";
import React, { useContext, useRef } from 'react';
import clsx from 'clsx';
import { getZIndexStyle } from '../utils';
import { BORDER_TOP_BOTTOM } from '../utils/constant';
import useHeight from '../hooks/use-height';
import TabbarContext from './TabbarContext';
import useMergedState from '../hooks/use-merged-state';
import ConfigProviderContext from '../config-provider/ConfigProviderContext';

const Tabbar = props => {
  const {
    prefixCls,
    createNamespace
  } = useContext(ConfigProviderContext);
  const [bem] = createNamespace('tabbar', prefixCls);
  const [current, setCurrent] = useMergedState({
    value: props.value,
    defaultValue: props.defaultValue
  });
  const root = useRef();
  const height = useHeight(root);

  const renderPlaceholder = renderContent => {
    return _jsx("div", Object.assign({
      className: clsx(bem('placeholder')),
      style: {
        height
      }
    }, {
      children: renderContent()
    }));
  }; // enable safe-area-inset-bottom by default when fixed


  const enableSafeArea = () => {
    var _a;

    return (_a = props.safeAreaInsetBottom) !== null && _a !== void 0 ? _a : props.fixed;
  };

  const setActive = active => {
    var _a;

    if (active !== props.value) {
      (_a = props.onChange) === null || _a === void 0 ? void 0 : _a.call(props, active);
      setCurrent(active);
    }
  };

  const renderTabbar = () => {
    const {
      fixed,
      zIndex,
      border
    } = props;
    return _jsx(TabbarContext.Provider, Object.assign({
      value: {
        parent: Object.assign(Object.assign({}, props), {
          value: current
        })
      }
    }, {
      children: _jsx("div", Object.assign({
        ref: root,
        style: Object.assign(Object.assign({}, props.style), getZIndexStyle(zIndex)),
        className: clsx(props.className, bem({
          fixed
        }), {
          [BORDER_TOP_BOTTOM]: border,
          'rv-safe-area-bottom': enableSafeArea()
        })
      }, {
        children: React.Children.toArray(props.children).filter(Boolean).map((child, index) => React.cloneElement(child, {
          setActive,
          index
        }))
      }))
    }));
  };

  if (props.fixed && props.placeholder) {
    return renderPlaceholder(renderTabbar);
  }

  return renderTabbar();
};

Tabbar.defaultProps = {
  fixed: true,
  border: true,
  defaultValue: 0
};
export default Tabbar;