// Copyright 1999-2025. WebPros International GmbH. All rights reserved.

import classNames from 'classnames';
import { useCallback, useLayoutEffect, useRef, useState } from 'react';
import { CLS_PREFIX } from '../../constants';
import calculateNodeHeight from './calculateNodeHeight';
import { jsx as _jsx } from "react/jsx-runtime";
const getMinMax = rows => {
  if (typeof rows === 'number') {
    return {
      minRows: rows
    };
  } else if (typeof rows === 'object' && typeof rows.min === 'number' && typeof rows.max === 'number') {
    return {
      minRows: rows.min,
      maxRows: rows.max
    };
  }
  return {};
};
const AVAILABLE_SIZES = new Set(['sm', 'md', 'lg', 'xl', 'fill']);

/**
 * `TextArea` is used for entering long text (like email body, descriptions, comments).
 * @since 1.9.0
 */
const TextArea = _ref => {
  let {
    baseClassName = `${CLS_PREFIX}textarea`,
    className,
    rows = 4,
    size = 'md',
    autoheight = false,
    onChange,
    style,
    ...props
  } = _ref;
  const rootRef = useRef(null);
  const useSizeModifier = size && AVAILABLE_SIZES.has(size);
  const {
    minRows,
    maxRows
  } = getMinMax(rows);
  const [heightStyle, setHeightStyle] = useState();
  const adjustHeight = useCallback(() => {
    if (!autoheight || !rootRef.current) {
      setHeightStyle(undefined);
      return;
    }
    setHeightStyle(calculateNodeHeight(rootRef.current, false, minRows, maxRows));
  }, [autoheight, maxRows, minRows]);
  useLayoutEffect(() => {
    adjustHeight();
  }, [adjustHeight]);
  const handleChange = e => {
    if (autoheight) {
      adjustHeight();
    }
    if (typeof onChange === 'function') {
      onChange(e);
    }
  };
  return /*#__PURE__*/_jsx("textarea", {
    ref: rootRef,
    className: classNames(baseClassName, {
      [`${baseClassName}--size-${size}`]: useSizeModifier
    }, className),
    style: {
      ...style,
      ...heightStyle
    },
    onChange: handleChange,
    rows: minRows,
    ...props
  });
};
export default TextArea;