'use strict';

Object.defineProperty(exports, '__esModule', { value: true });

var _rollupPluginBabelHelpers = require('../../../_virtual/_rollupPluginBabelHelpers.js');
var React = require('react');
var IconClose = require('../../_Icon/Icons/IconClose.js');
var IconSendOutline = require('../../_Icon/Icons/IconSendOutline.js');
var Input_styles = require('./Input.styles.js');
var Input_tokens = require('./Input.tokens.js');
var base = require('./variations/_view/base.js');
var base$1 = require('./variations/_size/base.js');
var defaultValueToString = require('./utils/defaultValueToString.js');
var matchSizeToIconSize = require('./utils/matchSizeToIconSize.js');

function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }

var React__default = /*#__PURE__*/_interopDefault(React);

var _excluded = ["value", "defaultValue", "onChange", "mode", "placeholder", "autoFocus", "minRows", "maxRows", "submitOnEnter", "clearOnSubmit", "attachments", "onAttachmentRemove", "onSend", "actionBefore", "actionAfter", "sendNode", "loading", "view", "size"];
var inputRoot = function inputRoot(Root) {
  return /*#__PURE__*/React.forwardRef(function (props, ref) {
    var outerValue = props.value,
      defaultValue = props.defaultValue,
      onChange = props.onChange,
      _props$mode = props.mode,
      mode = _props$mode === void 0 ? 'condensed' : _props$mode,
      placeholder = props.placeholder,
      _props$autoFocus = props.autoFocus,
      autoFocus = _props$autoFocus === void 0 ? false : _props$autoFocus,
      _props$minRows = props.minRows,
      minRows = _props$minRows === void 0 ? 1 : _props$minRows,
      _props$maxRows = props.maxRows,
      maxRows = _props$maxRows === void 0 ? 4 : _props$maxRows,
      _props$submitOnEnter = props.submitOnEnter,
      submitOnEnter = _props$submitOnEnter === void 0 ? true : _props$submitOnEnter,
      _props$clearOnSubmit = props.clearOnSubmit,
      clearOnSubmit = _props$clearOnSubmit === void 0 ? true : _props$clearOnSubmit,
      attachments = props.attachments,
      onAttachmentRemove = props.onAttachmentRemove,
      onSend = props.onSend,
      actionBefore = props.actionBefore,
      actionAfter = props.actionAfter,
      sendNode = props.sendNode,
      loading = props.loading,
      view = props.view,
      size = props.size,
      rest = _rollupPluginBabelHelpers.objectWithoutProperties(props, _excluded);
    var _useState = React.useState(mode === 'extended' ? 'textarea' : 'input'),
      _useState2 = _rollupPluginBabelHelpers.slicedToArray(_useState, 2),
      activeMode = _useState2[0],
      setActiveMode = _useState2[1];
    var _useState3 = React.useState(defaultValueToString.defaultValueToString(defaultValue)),
      _useState4 = _rollupPluginBabelHelpers.slicedToArray(_useState3, 2),
      innerValue = _useState4[0],
      setInnerValue = _useState4[1];
    var isCondensedInputMode = mode === 'condensed' && activeMode === 'input';
    var value = outerValue !== null && outerValue !== void 0 ? outerValue : innerValue;
    var setValue = function setValue(newValue) {
      setInnerValue(newValue);
      if (onChange) {
        onChange(newValue);
      }
    };
    var textareaRef = React.useRef(null);
    var focusAtEnd = function focusAtEnd() {
      var textareaElement = textareaRef.current;
      if (!textareaElement) {
        return;
      }
      textareaElement.focus();
      var end = textareaElement.value.length;
      textareaElement.setSelectionRange(end, end);
    };
    var insertAtSelection = function insertAtSelection(text) {
      var _textareaElement$sele, _textareaElement$sele2;
      var textareaElement = textareaRef.current;
      var selectionStart = (_textareaElement$sele = textareaElement === null || textareaElement === void 0 ? void 0 : textareaElement.selectionStart) !== null && _textareaElement$sele !== void 0 ? _textareaElement$sele : value.length;
      var selectionEnd = (_textareaElement$sele2 = textareaElement === null || textareaElement === void 0 ? void 0 : textareaElement.selectionEnd) !== null && _textareaElement$sele2 !== void 0 ? _textareaElement$sele2 : value.length;
      setValue("".concat(value.slice(0, selectionStart)).concat(text).concat(value.slice(selectionEnd)));
    };
    var switchToTextarea = function switchToTextarea() {
      if (mode === 'extended' || activeMode === 'textarea') {
        return;
      }
      setActiveMode('textarea');
      requestAnimationFrame(function () {
        var _textareaRef$current, _textareaRef$current2;
        focusAtEnd();
        (_textareaRef$current = textareaRef.current) === null || _textareaRef$current === void 0 || _textareaRef$current.scrollTo({
          top: (_textareaRef$current2 = textareaRef.current) === null || _textareaRef$current2 === void 0 ? void 0 : _textareaRef$current2.scrollHeight
        });
      });
    };
    var switchToInput = function switchToInput() {
      if (mode === 'extended' || activeMode === 'input') {
        return;
      }
      setActiveMode('input');
      requestAnimationFrame(focusAtEnd);
    };
    var handleSendMessage = function handleSendMessage() {
      if (onSend) {
        onSend(value);
      }
      if (clearOnSubmit) {
        setValue('');
        if (mode === 'condensed' && activeMode === 'textarea') {
          switchToInput();
        }
      }
    };
    var handleKeyDown = function handleKeyDown(event) {
      if (isCondensedInputMode) {
        if (event.key !== 'Enter') {
          return;
        }
        event.preventDefault();
        if (event.shiftKey) {
          insertAtSelection('\n');
          switchToTextarea();
          return;
        }
        if (submitOnEnter) {
          handleSendMessage();
          return;
        }
        switchToTextarea();
        return;
      }
      if (event.defaultPrevented || event.key !== 'Enter' || event.shiftKey || !submitOnEnter) {
        return;
      }
      event.preventDefault();
      handleSendMessage();
    };
    var handlePaste = function handlePaste(event) {
      if (!isCondensedInputMode) {
        return;
      }
      var pastedText = event.clipboardData.getData('text');
      if (!pastedText.includes('\n')) {
        return;
      }
      event.preventDefault();
      insertAtSelection(pastedText);
      switchToTextarea();
    };
    var handleChange = function handleChange(event) {
      setValue(event.target.value);
      if (event.target.value.length === 0 && mode === 'condensed' && activeMode === 'textarea') {
        switchToInput();
      }
    };
    var resize = function resize() {
      var element = textareaRef.current;
      if (!element) {
        return;
      }
      var computedStyle = window.getComputedStyle(element);
      var lineHeight = Number.parseFloat(computedStyle.lineHeight);
      var safeLineHeight = Number.isFinite(lineHeight) ? lineHeight : Number.parseFloat(computedStyle.fontSize) * 1.2 || 16;
      var minHeight = safeLineHeight * minRows;
      var maxHeight = safeLineHeight * maxRows;
      element.style.height = 'auto';
      var newHeight = Math.min(Math.max(element.scrollHeight, minHeight), maxHeight);
      element.style.height = "".concat(newHeight, "px");
      element.style.overflowY = element.scrollHeight > maxHeight ? 'auto' : 'hidden';
    };

    // Переключение, когда однострочный текст перестал влезать в condensed-режиме
    var checkOverflow = function checkOverflow() {
      var element = textareaRef.current;
      if (!element) {
        return;
      }
      if (element.scrollWidth > element.clientWidth) {
        switchToTextarea();
      }
    };

    // Проверяем overflow при каждом вводе
    React.useLayoutEffect(function () {
      if (!isCondensedInputMode) return;
      checkOverflow();
    }, [isCondensedInputMode, value]);

    // Проверяем overflow при ресайзе экрана
    React.useLayoutEffect(function () {
      if (!isCondensedInputMode) {
        return;
      }
      var element = textareaRef.current;
      if (!element) {
        return;
      }
      var resizeObserver = new ResizeObserver(checkOverflow);
      resizeObserver.observe(element);
      return function () {
        resizeObserver.disconnect();
      };
    }, [isCondensedInputMode]);

    // Авторесайз textarea по высоте
    React.useLayoutEffect(function () {
      if (isCondensedInputMode) {
        return;
      }
      resize();
    }, [isCondensedInputMode, value, minRows, maxRows]);
    var textArea = /*#__PURE__*/React__default.default.createElement(Input_styles.TextArea, {
      "data-condensed": isCondensedInputMode,
      ref: textareaRef,
      value: value,
      rows: isCondensedInputMode ? 1 : minRows,
      wrap: isCondensedInputMode ? 'off' : undefined,
      autoFocus: autoFocus,
      placeholder: placeholder,
      onKeyDown: handleKeyDown,
      onPaste: handlePaste,
      onChange: handleChange
    });
    return /*#__PURE__*/React__default.default.createElement(Root, _rollupPluginBabelHelpers.extends({
      ref: ref,
      size: size,
      view: view
    }, rest), attachments && attachments.length > 0 && /*#__PURE__*/React__default.default.createElement(Input_styles.AttachmentsList, null, attachments.map(function (attachment) {
      var id = attachment.id,
        type = attachment.type,
        label = attachment.label,
        attachedSize = attachment.size,
        thumbUrl = attachment.thumbUrl;
      var handleRemove = function handleRemove() {
        return onAttachmentRemove === null || onAttachmentRemove === void 0 ? void 0 : onAttachmentRemove(attachment);
      };
      if (type === 'image') {
        return /*#__PURE__*/React__default.default.createElement(Input_styles.AttachedImage, {
          key: id,
          tabIndex: 0,
          onKeyDown: function onKeyDown(event) {
            if (event.key === 'Enter') {
              event.preventDefault();
              handleRemove();
            }
          }
        }, /*#__PURE__*/React__default.default.createElement(Input_styles.AttachedImageOverlay, {
          className: Input_tokens.classes.attachedOverlay
        }, /*#__PURE__*/React__default.default.createElement(Input_styles.RemoveButton, {
          onClick: handleRemove,
          tabIndex: -1
        }, /*#__PURE__*/React__default.default.createElement(IconClose.IconClose, {
          size: matchSizeToIconSize.matchSizeToIconSize(size),
          color: "inherit"
        }))), /*#__PURE__*/React__default.default.createElement(Input_styles.Thumb, {
          src: thumbUrl,
          alt: label
        }));
      }
      return /*#__PURE__*/React__default.default.createElement(Input_styles.AttachedFile, {
        key: id,
        filename: label || '',
        description: attachedSize,
        thumbUrl: thumbUrl,
        actionContent: /*#__PURE__*/React__default.default.createElement(IconClose.IconClose, {
          size: matchSizeToIconSize.matchSizeToIconSize(size),
          color: "inherit"
        }),
        onActionClick: handleRemove
      });
    })), !isCondensedInputMode && /*#__PURE__*/React__default.default.createElement(Input_styles.TextAreaWrapper, null, textArea), /*#__PURE__*/React__default.default.createElement(Input_styles.Footer, null, /*#__PURE__*/React__default.default.createElement(Input_styles.ActionBefore, null, actionBefore), /*#__PURE__*/React__default.default.createElement(Input_styles.InputFieldWrapper, null, isCondensedInputMode && textArea), /*#__PURE__*/React__default.default.createElement(Input_styles.ActionAfter, null, actionAfter), sendNode || /*#__PURE__*/React__default.default.createElement(Input_styles.SubmitButton, {
      onClick: handleSendMessage,
      isLoading: loading
    }, /*#__PURE__*/React__default.default.createElement(IconSendOutline.IconSendOutline, {
      size: matchSizeToIconSize.matchSizeToIconSize(size),
      color: "inherit"
    }))));
  });
};
var inputConfig = {
  name: 'Input',
  tag: 'div',
  layout: inputRoot,
  base: Input_styles.base,
  variations: {
    view: {
      css: base.base
    },
    size: {
      css: base$1.base
    }
  },
  defaults: {
    view: 'default',
    size: 'm'
  }
};

exports.inputConfig = inputConfig;
exports.inputRoot = inputRoot;
