function _array_like_to_array(arr, len) {
    if (len == null || len > arr.length) len = arr.length;
    for(var i = 0, arr2 = new Array(len); i < len; i++)arr2[i] = arr[i];
    return arr2;
}
function _array_with_holes(arr) {
    if (Array.isArray(arr)) return arr;
}
function _define_property(obj, key, value) {
    if (key in obj) {
        Object.defineProperty(obj, key, {
            value: value,
            enumerable: true,
            configurable: true,
            writable: true
        });
    } else {
        obj[key] = value;
    }
    return obj;
}
function _iterable_to_array_limit(arr, i) {
    var _i = arr == null ? null : typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"];
    if (_i == null) return;
    var _arr = [];
    var _n = true;
    var _d = false;
    var _s, _e;
    try {
        for(_i = _i.call(arr); !(_n = (_s = _i.next()).done); _n = true){
            _arr.push(_s.value);
            if (i && _arr.length === i) break;
        }
    } catch (err) {
        _d = true;
        _e = err;
    } finally{
        try {
            if (!_n && _i["return"] != null) _i["return"]();
        } finally{
            if (_d) throw _e;
        }
    }
    return _arr;
}
function _non_iterable_rest() {
    throw new TypeError("Invalid attempt to destructure non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
}
function _object_spread(target) {
    for(var i = 1; i < arguments.length; i++){
        var source = arguments[i] != null ? arguments[i] : {};
        var ownKeys = Object.keys(source);
        if (typeof Object.getOwnPropertySymbols === "function") {
            ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function(sym) {
                return Object.getOwnPropertyDescriptor(source, sym).enumerable;
            }));
        }
        ownKeys.forEach(function(key) {
            _define_property(target, key, source[key]);
        });
    }
    return target;
}
function _object_without_properties(source, excluded) {
    if (source == null) return {};
    var target = {}, sourceKeys, key, i;
    if (typeof Reflect !== "undefined" && Reflect.ownKeys) {
        sourceKeys = Reflect.ownKeys(source);
        for(i = 0; i < sourceKeys.length; i++){
            key = sourceKeys[i];
            if (excluded.indexOf(key) >= 0) continue;
            if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue;
            target[key] = source[key];
        }
        return target;
    }
    target = _object_without_properties_loose(source, excluded);
    if (Object.getOwnPropertySymbols) {
        sourceKeys = Object.getOwnPropertySymbols(source);
        for(i = 0; i < sourceKeys.length; i++){
            key = sourceKeys[i];
            if (excluded.indexOf(key) >= 0) continue;
            if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue;
            target[key] = source[key];
        }
    }
    return target;
}
function _object_without_properties_loose(source, excluded) {
    if (source == null) return {};
    var target = {}, sourceKeys = Object.getOwnPropertyNames(source), key, i;
    for(i = 0; i < sourceKeys.length; i++){
        key = sourceKeys[i];
        if (excluded.indexOf(key) >= 0) continue;
        if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue;
        target[key] = source[key];
    }
    return target;
}
function _sliced_to_array(arr, i) {
    return _array_with_holes(arr) || _iterable_to_array_limit(arr, i) || _unsupported_iterable_to_array(arr, i) || _non_iterable_rest();
}
function _unsupported_iterable_to_array(o, minLen) {
    if (!o) return;
    if (typeof o === "string") return _array_like_to_array(o, minLen);
    var n = Object.prototype.toString.call(o).slice(8, -1);
    if (n === "Object" && o.constructor) n = o.constructor.name;
    if (n === "Map" || n === "Set") return Array.from(n);
    if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _array_like_to_array(o, minLen);
}
import React, { forwardRef, useRef, useState, useLayoutEffect } from "react";
import { IconClose, IconSendOutline } from "../../_Icon";
import { AttachedFile, AttachedImage, AttachedImageOverlay, AttachmentsList, base, TextArea, TextAreaWrapper, Thumb, RemoveButton, Footer, SubmitButton, InputFieldWrapper, ActionBefore, ActionAfter } from "./Input.styles";
import { classes } from "./Input.tokens";
import { base as viewCSS } from "./variations/_view/base";
import { base as sizeCSS } from "./variations/_size/base";
import { matchSizeToIconSize, defaultValueToString } from "./utils";
export var inputRoot = function inputRoot(Root) {
    return /*#__PURE__*/ 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 = _object_without_properties(props, [
            "value",
            "defaultValue",
            "onChange",
            "mode",
            "placeholder",
            "autoFocus",
            "minRows",
            "maxRows",
            "submitOnEnter",
            "clearOnSubmit",
            "attachments",
            "onAttachmentRemove",
            "onSend",
            "actionBefore",
            "actionAfter",
            "sendNode",
            "loading",
            "view",
            "size"
        ]);
        var _useState = _sliced_to_array(useState(mode === 'extended' ? 'textarea' : 'input'), 2), activeMode = _useState[0], setActiveMode = _useState[1];
        var _useState1 = _sliced_to_array(useState(defaultValueToString(defaultValue)), 2), innerValue = _useState1[0], setInnerValue = _useState1[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 = 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 _ref, _ref1;
            var textareaElement = textareaRef.current;
            var selectionStart = (_ref = textareaElement === null || textareaElement === void 0 ? void 0 : textareaElement.selectionStart) !== null && _ref !== void 0 ? _ref : value.length;
            var selectionEnd = (_ref1 = textareaElement === null || textareaElement === void 0 ? void 0 : textareaElement.selectionEnd) !== null && _ref1 !== void 0 ? _ref1 : 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_current1;
                focusAtEnd();
                (_textareaRef_current1 = textareaRef.current) === null || _textareaRef_current1 === void 0 ? void 0 : _textareaRef_current1.scrollTo({
                    top: (_textareaRef_current = textareaRef.current) === null || _textareaRef_current === void 0 ? void 0 : _textareaRef_current.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 при каждом вводе
        useLayoutEffect(function() {
            if (!isCondensedInputMode) return;
            checkOverflow();
        }, [
            isCondensedInputMode,
            value
        ]);
        // Проверяем overflow при ресайзе экрана
        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 по высоте
        useLayoutEffect(function() {
            if (isCondensedInputMode) {
                return;
            }
            resize();
        }, [
            isCondensedInputMode,
            value,
            minRows,
            maxRows
        ]);
        var textArea = /*#__PURE__*/ React.createElement(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.createElement(Root, _object_spread({
            ref: ref,
            size: size,
            view: view
        }, rest), attachments && attachments.length > 0 && /*#__PURE__*/ React.createElement(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.createElement(AttachedImage, {
                    key: id,
                    tabIndex: 0,
                    onKeyDown: function onKeyDown(event) {
                        if (event.key === 'Enter') {
                            event.preventDefault();
                            handleRemove();
                        }
                    }
                }, /*#__PURE__*/ React.createElement(AttachedImageOverlay, {
                    className: classes.attachedOverlay
                }, /*#__PURE__*/ React.createElement(RemoveButton, {
                    onClick: handleRemove,
                    tabIndex: -1
                }, /*#__PURE__*/ React.createElement(IconClose, {
                    size: matchSizeToIconSize(size),
                    color: "inherit"
                }))), /*#__PURE__*/ React.createElement(Thumb, {
                    src: thumbUrl,
                    alt: label
                }));
            }
            return /*#__PURE__*/ React.createElement(AttachedFile, {
                key: id,
                filename: label || '',
                description: attachedSize,
                thumbUrl: thumbUrl,
                actionContent: /*#__PURE__*/ React.createElement(IconClose, {
                    size: matchSizeToIconSize(size),
                    color: "inherit"
                }),
                onActionClick: handleRemove
            });
        })), !isCondensedInputMode && /*#__PURE__*/ React.createElement(TextAreaWrapper, null, textArea), /*#__PURE__*/ React.createElement(Footer, null, /*#__PURE__*/ React.createElement(ActionBefore, null, actionBefore), /*#__PURE__*/ React.createElement(InputFieldWrapper, null, isCondensedInputMode && textArea), /*#__PURE__*/ React.createElement(ActionAfter, null, actionAfter), sendNode || /*#__PURE__*/ React.createElement(SubmitButton, {
            onClick: handleSendMessage,
            isLoading: loading
        }, /*#__PURE__*/ React.createElement(IconSendOutline, {
            size: matchSizeToIconSize(size),
            color: "inherit"
        }))));
    });
};
export var inputConfig = {
    name: 'Input',
    tag: 'div',
    layout: inputRoot,
    base: base,
    variations: {
        view: {
            css: viewCSS
        },
        size: {
            css: sizeCSS
        }
    },
    defaults: {
        view: 'default',
        size: 'm'
    }
};
