"use strict";
Object.defineProperty(exports, "__esModule", {
    value: true
});
function _export(target, all) {
    for(var name in all)Object.defineProperty(target, name, {
        enumerable: true,
        get: Object.getOwnPropertyDescriptor(all, name).get
    });
}
_export(exports, {
    get inputConfig () {
        return inputConfig;
    },
    get inputRoot () {
        return inputRoot;
    }
});
const _react = /*#__PURE__*/ _interop_require_wildcard(require("react"));
const _Icon = require("../../_Icon");
const _Inputstyles = require("./Input.styles");
const _Inputtokens = require("./Input.tokens");
const _base = require("./variations/_view/base");
const _base1 = require("./variations/_size/base");
const _utils = require("./utils");
function _getRequireWildcardCache(nodeInterop) {
    if (typeof WeakMap !== "function") return null;
    var cacheBabelInterop = new WeakMap();
    var cacheNodeInterop = new WeakMap();
    return (_getRequireWildcardCache = function(nodeInterop) {
        return nodeInterop ? cacheNodeInterop : cacheBabelInterop;
    })(nodeInterop);
}
function _interop_require_wildcard(obj, nodeInterop) {
    if (!nodeInterop && obj && obj.__esModule) {
        return obj;
    }
    if (obj === null || typeof obj !== "object" && typeof obj !== "function") {
        return {
            default: obj
        };
    }
    var cache = _getRequireWildcardCache(nodeInterop);
    if (cache && cache.has(obj)) {
        return cache.get(obj);
    }
    var newObj = {
        __proto__: null
    };
    var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor;
    for(var key in obj){
        if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) {
            var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null;
            if (desc && (desc.get || desc.set)) {
                Object.defineProperty(newObj, key, desc);
            } else {
                newObj[key] = obj[key];
            }
        }
    }
    newObj.default = obj;
    if (cache) {
        cache.set(obj, newObj);
    }
    return newObj;
}
const inputRoot = (Root)=>/*#__PURE__*/ (0, _react.forwardRef)((props, ref)=>{
        const { value: outerValue, defaultValue, onChange, mode = 'condensed', placeholder, autoFocus = false, minRows = 1, maxRows = 4, submitOnEnter = true, clearOnSubmit = true, attachments, onAttachmentRemove, onSend, actionBefore, actionAfter, sendNode, loading, view, size, ...rest } = props;
        const [activeMode, setActiveMode] = (0, _react.useState)(mode === 'extended' ? 'textarea' : 'input');
        const [innerValue, setInnerValue] = (0, _react.useState)((0, _utils.defaultValueToString)(defaultValue));
        const isCondensedInputMode = mode === 'condensed' && activeMode === 'input';
        const value = outerValue ?? innerValue;
        const setValue = (newValue)=>{
            setInnerValue(newValue);
            if (onChange) {
                onChange(newValue);
            }
        };
        const textareaRef = (0, _react.useRef)(null);
        const focusAtEnd = ()=>{
            const textareaElement = textareaRef.current;
            if (!textareaElement) {
                return;
            }
            textareaElement.focus();
            const end = textareaElement.value.length;
            textareaElement.setSelectionRange(end, end);
        };
        const insertAtSelection = (text)=>{
            const textareaElement = textareaRef.current;
            const selectionStart = textareaElement?.selectionStart ?? value.length;
            const selectionEnd = textareaElement?.selectionEnd ?? value.length;
            setValue(`${value.slice(0, selectionStart)}${text}${value.slice(selectionEnd)}`);
        };
        const switchToTextarea = ()=>{
            if (mode === 'extended' || activeMode === 'textarea') {
                return;
            }
            setActiveMode('textarea');
            requestAnimationFrame(()=>{
                focusAtEnd();
                textareaRef.current?.scrollTo({
                    top: textareaRef.current?.scrollHeight
                });
            });
        };
        const switchToInput = ()=>{
            if (mode === 'extended' || activeMode === 'input') {
                return;
            }
            setActiveMode('input');
            requestAnimationFrame(focusAtEnd);
        };
        const handleSendMessage = ()=>{
            if (onSend) {
                onSend(value);
            }
            if (clearOnSubmit) {
                setValue('');
                if (mode === 'condensed' && activeMode === 'textarea') {
                    switchToInput();
                }
            }
        };
        const 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();
        };
        const handlePaste = (event)=>{
            if (!isCondensedInputMode) {
                return;
            }
            const pastedText = event.clipboardData.getData('text');
            if (!pastedText.includes('\n')) {
                return;
            }
            event.preventDefault();
            insertAtSelection(pastedText);
            switchToTextarea();
        };
        const handleChange = (event)=>{
            setValue(event.target.value);
            if (event.target.value.length === 0 && mode === 'condensed' && activeMode === 'textarea') {
                switchToInput();
            }
        };
        const resize = ()=>{
            const element = textareaRef.current;
            if (!element) {
                return;
            }
            const computedStyle = window.getComputedStyle(element);
            const lineHeight = Number.parseFloat(computedStyle.lineHeight);
            const safeLineHeight = Number.isFinite(lineHeight) ? lineHeight : Number.parseFloat(computedStyle.fontSize) * 1.2 || 16;
            const minHeight = safeLineHeight * minRows;
            const maxHeight = safeLineHeight * maxRows;
            element.style.height = 'auto';
            const newHeight = Math.min(Math.max(element.scrollHeight, minHeight), maxHeight);
            element.style.height = `${newHeight}px`;
            element.style.overflowY = element.scrollHeight > maxHeight ? 'auto' : 'hidden';
        };
        // Переключение, когда однострочный текст перестал влезать в condensed-режиме
        const checkOverflow = ()=>{
            const element = textareaRef.current;
            if (!element) {
                return;
            }
            if (element.scrollWidth > element.clientWidth) {
                switchToTextarea();
            }
        };
        // Проверяем overflow при каждом вводе
        (0, _react.useLayoutEffect)(()=>{
            if (!isCondensedInputMode) return;
            checkOverflow();
        }, [
            isCondensedInputMode,
            value
        ]);
        // Проверяем overflow при ресайзе экрана
        (0, _react.useLayoutEffect)(()=>{
            if (!isCondensedInputMode) {
                return;
            }
            const element = textareaRef.current;
            if (!element) {
                return;
            }
            const resizeObserver = new ResizeObserver(checkOverflow);
            resizeObserver.observe(element);
            return ()=>{
                resizeObserver.disconnect();
            };
        }, [
            isCondensedInputMode
        ]);
        // Авторесайз textarea по высоте
        (0, _react.useLayoutEffect)(()=>{
            if (isCondensedInputMode) {
                return;
            }
            resize();
        }, [
            isCondensedInputMode,
            value,
            minRows,
            maxRows
        ]);
        const textArea = /*#__PURE__*/ _react.default.createElement(_Inputstyles.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.createElement(Root, {
            ref: ref,
            size: size,
            view: view,
            ...rest
        }, attachments && attachments.length > 0 && /*#__PURE__*/ _react.default.createElement(_Inputstyles.AttachmentsList, null, attachments.map((attachment)=>{
            const { id, type, label, size: attachedSize, thumbUrl } = attachment;
            const handleRemove = ()=>onAttachmentRemove?.(attachment);
            if (type === 'image') {
                return /*#__PURE__*/ _react.default.createElement(_Inputstyles.AttachedImage, {
                    key: id,
                    tabIndex: 0,
                    onKeyDown: (event)=>{
                        if (event.key === 'Enter') {
                            event.preventDefault();
                            handleRemove();
                        }
                    }
                }, /*#__PURE__*/ _react.default.createElement(_Inputstyles.AttachedImageOverlay, {
                    className: _Inputtokens.classes.attachedOverlay
                }, /*#__PURE__*/ _react.default.createElement(_Inputstyles.RemoveButton, {
                    onClick: handleRemove,
                    tabIndex: -1
                }, /*#__PURE__*/ _react.default.createElement(_Icon.IconClose, {
                    size: (0, _utils.matchSizeToIconSize)(size),
                    color: "inherit"
                }))), /*#__PURE__*/ _react.default.createElement(_Inputstyles.Thumb, {
                    src: thumbUrl,
                    alt: label
                }));
            }
            return /*#__PURE__*/ _react.default.createElement(_Inputstyles.AttachedFile, {
                key: id,
                filename: label || '',
                description: attachedSize,
                thumbUrl: thumbUrl,
                actionContent: /*#__PURE__*/ _react.default.createElement(_Icon.IconClose, {
                    size: (0, _utils.matchSizeToIconSize)(size),
                    color: "inherit"
                }),
                onActionClick: handleRemove
            });
        })), !isCondensedInputMode && /*#__PURE__*/ _react.default.createElement(_Inputstyles.TextAreaWrapper, null, textArea), /*#__PURE__*/ _react.default.createElement(_Inputstyles.Footer, null, /*#__PURE__*/ _react.default.createElement(_Inputstyles.ActionBefore, null, actionBefore), /*#__PURE__*/ _react.default.createElement(_Inputstyles.InputFieldWrapper, null, isCondensedInputMode && textArea), /*#__PURE__*/ _react.default.createElement(_Inputstyles.ActionAfter, null, actionAfter), sendNode || /*#__PURE__*/ _react.default.createElement(_Inputstyles.SubmitButton, {
            onClick: handleSendMessage,
            isLoading: loading
        }, /*#__PURE__*/ _react.default.createElement(_Icon.IconSendOutline, {
            size: (0, _utils.matchSizeToIconSize)(size),
            color: "inherit"
        }))));
    });
const inputConfig = {
    name: 'Input',
    tag: 'div',
    layout: inputRoot,
    base: _Inputstyles.base,
    variations: {
        view: {
            css: _base.base
        },
        size: {
            css: _base1.base
        }
    },
    defaults: {
        view: 'default',
        size: 'm'
    }
};
