import _extends from "@babel/runtime/helpers/extends";
// Copyright 1999-2020. Plesk International GmbH. All rights reserved.
import React, { useState, useContext } from 'react';
import classNames from 'classnames';
import Measure from 'react-measure';
import { CLS_PREFIX } from '../../constants';
import VerticalContext, { VERTICAL_BREAKPOINT } from '../VerticalContext';

/**
 * `Columns` component is used for creating of multi-column layouts.
 * @since 2.6.0
 */
const Columns = ({
  baseClassName = `${CLS_PREFIX}columns`,
  className,
  children,
  vertical: verticalProp,
  gap,
  ...props
}) => {
  // eslint-disable-next-line prefer-const
  let [vertical, setVertical] = useState(false);
  const verticalContext = useContext(VerticalContext);

  if (verticalProp === undefined) {
    verticalProp = typeof verticalContext === 'undefined' ? VERTICAL_BREAKPOINT : verticalContext;
  }

  if (typeof verticalProp === 'boolean') {
    vertical = verticalProp;
  }

  const handleResize = ({
    bounds
  }) => {
    setVertical(bounds.width < verticalProp);
  };

  const createRoot = measureRef => /*#__PURE__*/React.createElement("div", _extends({
    ref: measureRef,
    className: classNames(baseClassName, {
      [`${baseClassName}--vertical`]: vertical,
      [`${baseClassName}--gap-${gap}`]: gap
    }, className)
  }, props), /*#__PURE__*/React.createElement(VerticalContext.Provider, {
    value: vertical
  }, children));

  if (typeof verticalProp === 'number') {
    return /*#__PURE__*/React.createElement(Measure, {
      bounds: true,
      onResize: handleResize
    }, ({
      measureRef
    }) => createRoot(measureRef));
  }

  return createRoot();
};

export default Columns;