"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 codeInputConfig () {
        return codeInputConfig;
    },
    get codeInputRoot () {
        return codeInputRoot;
    }
});
const _react = /*#__PURE__*/ _interop_require_wildcard(require("react"));
const _classnames = /*#__PURE__*/ _interop_require_default(require("classnames"));
const _hooks = require("../../hooks");
const _utils = require("../../utils");
const _constants = require("../../utils/constants");
const _utils1 = require("./utils");
const _CodeInputtokens = require("./CodeInput.tokens");
const _CodeInputstyles = require("./CodeInput.styles");
const _base = require("./variations/_view/base");
const _base1 = require("./variations/_size/base");
const _base2 = require("./variations/_disabled/base");
function _interop_require_default(obj) {
    return obj && obj.__esModule ? obj : {
        default: obj
    };
}
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 codeInputRoot = (Root)=>/*#__PURE__*/ (0, _react.forwardRef)(({ className, placeholder, autoFocus, codeLength = 6, caption, captionAlign = 'left', width, view, size, hidden, disabled, isError, allowedSymbols = _constants.ONLY_DIGITS_PATTERN, itemErrorBehavior = 'remove-symbol', codeErrorBehavior = 'remove-code', autoComplete = 'one-time-code', inputMode, setIsError, onChange, onFullCodeEnter, ...rest }, ref)=>{
        const [code, setCode] = (0, _react.useState)((0, _utils1.getCodeValue)(codeLength, ''));
        const [originalValue, setOriginalValue] = (0, _react.useState)(code.join(''));
        const inputRefs = (0, _react.useRef)([]);
        const inputContainerRef = (0, _react.useRef)(null);
        const captionRef = (0, _react.useRef)(null);
        const fieldPattern = (0, _utils1.getFieldPattern)(allowedSymbols);
        const placeholderValue = (0, _utils1.getPlaceholderValue)(codeLength, placeholder);
        const parts = codeLength === 6 ? 2 : 1;
        const widthValue = width ? (0, _utils.getSizeValueFromProp)(width, 'rem') : undefined;
        const getLastActiveIndex = ()=>{
            if (code.length && code.length < codeLength) {
                return code.length;
            }
            const lastEmptyIndex = code.findIndex((digit)=>digit === '');
            return lastEmptyIndex >= 0 ? lastEmptyIndex : codeLength - 1;
        };
        const handleClick = ()=>{
            if (disabled) {
                return;
            }
            const lastActiveIndex = getLastActiveIndex();
            if (inputRefs.current[lastActiveIndex]) {
                inputRefs.current[lastActiveIndex].focus();
            }
        };
        const handleOnKeyDown = (event, index, type)=>{
            if (disabled) {
                return;
            }
            const { key } = event;
            if (_constants.FORBIDDEN_KEYS.includes(key)) {
                event.preventDefault();
                return;
            }
            if (key === _constants.BACKSPACE_KEY) {
                if (index > 0 && code[index] === '') {
                    inputRefs.current[index - 1]?.focus();
                }
            }
            if (type === 'circle') {
                event.preventDefault();
                handleAddSymbol(key, index);
                inputRefs.current[index]?.focus();
            }
        };
        const codeSetter = (newCode)=>{
            setCode(newCode);
            setOriginalValue(newCode.join(''));
            if (onChange) {
                onChange(newCode.join(''));
            }
        };
        const handleChange = (event, index)=>{
            if (disabled) {
                return;
            }
            const rawSymbol = event.currentTarget.value;
            // На мобильных устройствах вставка вызывает onChange по 1 символу
            if (rawSymbol.length > 1) {
                const newCode = [
                    ...code
                ];
                const pastedData = (fieldPattern ? rawSymbol.split('').map((symb)=>symb.match(fieldPattern)?.[0] || '').filter(Boolean) : rawSymbol.split('')).slice(0, codeLength - index);
                pastedData.forEach((element, i)=>{
                    newCode[index + i] = element;
                });
                const activeIndex = Math.min(index + pastedData.length, codeLength - 1);
                inputRefs.current[activeIndex]?.focus();
                codeSetter(newCode);
                return;
            }
            const symbol = rawSymbol.charAt(rawSymbol.length - 1);
            handleAddSymbol(symbol, index);
        };
        const handleAddSymbol = (symbol, index)=>{
            const newCode = [
                ...code
            ];
            inputRefs.current[index]?.classList.remove(_CodeInputtokens.classes.itemError);
            if (isError) {
                captionRef.current?.classList.remove(_CodeInputtokens.classes.captionError);
                if (codeErrorBehavior === 'keep') {
                    inputContainerRef.current?.classList.remove(_CodeInputtokens.classes.codeError, _CodeInputtokens.classes.codeErrorAnimation);
                }
                if (setIsError) {
                    setIsError(false);
                }
            }
            if (!fieldPattern) {
                newCode[index] = symbol;
                codeSetter(newCode);
                if (symbol && index < codeLength - 1) {
                    inputRefs.current[index + 1]?.focus();
                }
                return;
            }
            if (!symbol) {
                newCode[index] = '';
                codeSetter(newCode);
                return;
            }
            if (fieldPattern.test(symbol)) {
                newCode[index] = symbol.charAt(symbol.length - 1);
                codeSetter(newCode);
                if (index < codeLength - 1) {
                    inputRefs.current[index + 1]?.focus();
                }
            } else {
                newCode[index] = symbol.charAt(symbol.length - 1);
                (0, _utils1.handleItemError)({
                    currentSymbol: symbol,
                    itemErrorBehavior,
                    index,
                    newCode,
                    inputRefs,
                    inputContainerRef,
                    codeSetter
                });
            }
        };
        const handlePaste = (event)=>{
            const newCode = [
                ...code
            ];
            if (disabled) {
                return;
            }
            event.preventDefault();
            const rawData = event.clipboardData.getData('text/plain');
            const pastedData = (fieldPattern ? rawData.split('').map((symb)=>symb.match(fieldPattern)?.[0] || '').filter(Boolean) || [] : rawData.split('')).slice(0, codeLength);
            pastedData.forEach((element, index)=>{
                newCode[index] = element;
            });
            const activeIndex = Math.min(pastedData.length, codeLength - 1);
            inputRefs.current[activeIndex]?.focus();
            codeSetter(newCode);
        };
        const handleFullCodeEnter = (0, _react.useCallback)((fullCode)=>{
            if (onFullCodeEnter) {
                onFullCodeEnter(fullCode);
            }
        }, []);
        (0, _hooks.useCodeHook)({
            inputRefs,
            codeLength,
            disabled,
            autoFocus,
            originalValue,
            getLastActiveIndex,
            handleFullCodeEnter
        });
        (0, _hooks.useDidMountEffect)(()=>{
            if (isError) {
                (0, _utils1.handleCodeError)({
                    codeLength,
                    codeErrorBehavior,
                    currentCode: code,
                    inputRefs,
                    inputContainerRef,
                    captionRef,
                    setCode,
                    codeSetter
                });
            }
        }, [
            isError
        ]);
        return /*#__PURE__*/ _react.default.createElement(Root, {
            ref: ref,
            view: view,
            size: size,
            disabled: disabled,
            onClick: handleClick,
            className: (0, _classnames.default)(className, {
                [_CodeInputtokens.classes.captionAlignLeft]: captionAlign === 'left'
            }),
            ...rest
        }, /*#__PURE__*/ _react.default.createElement(_CodeInputstyles.CodeWrapper, {
            ref: inputContainerRef
        }, [
            ...Array(parts)
        ].map((_, partIndex)=>/*#__PURE__*/ _react.default.createElement(_react.Fragment, {
                key: partIndex
            }, /*#__PURE__*/ _react.default.createElement(_CodeInputstyles.CodeGroup, {
                role: "group"
            }, [
                ...Array(codeLength / parts)
            ].map((_, i)=>{
                const inputCorrectIndex = i + codeLength / parts * partIndex;
                return /*#__PURE__*/ _react.default.createElement(_CodeInputstyles.ItemWrapper, {
                    key: String(partIndex + i + partIndex * i)
                }, (!code[inputCorrectIndex] || Boolean(code[inputCorrectIndex]) && hidden) && /*#__PURE__*/ _react.default.createElement(_CodeInputstyles.ItemCircle, {
                    role: "tab",
                    tabIndex: originalValue.length === inputCorrectIndex ? 0 : -1,
                    onKeyDown: (e)=>{
                        handleOnKeyDown(e, inputCorrectIndex, 'circle');
                    },
                    className: (0, _classnames.default)([
                        Boolean(code[inputCorrectIndex]) && hidden ? _CodeInputtokens.classes.itemCirlceFilled : '',
                        `${_CodeInputtokens.classes.itemCircle}-${inputCorrectIndex}`
                    ])
                }), /*#__PURE__*/ _react.default.createElement(_CodeInputstyles.ItemInput, {
                    ref: (element)=>{
                        inputRefs.current[inputCorrectIndex] = element;
                    },
                    className: (0, _classnames.default)({
                        [_CodeInputtokens.classes.hoverEnabled]: inputCorrectIndex >= originalValue.length
                    }),
                    hide: hidden,
                    inputMode: inputMode,
                    value: code[inputCorrectIndex] || '',
                    tabIndex: originalValue.length === inputCorrectIndex ? 0 : -1,
                    autoComplete: autoComplete,
                    onChange: (e)=>{
                        handleChange(e, inputCorrectIndex);
                    },
                    onKeyDown: (e)=>{
                        handleOnKeyDown(e, inputCorrectIndex);
                    },
                    onPaste: handlePaste,
                    ...placeholderValue && {
                        placeholder: placeholderValue[inputCorrectIndex]
                    }
                }));
            })), partIndex !== parts - 1 && /*#__PURE__*/ _react.default.createElement(_CodeInputstyles.Separator, null)))), caption && /*#__PURE__*/ _react.default.createElement(_CodeInputstyles.CaptionWrapper, {
            ref: captionRef,
            captionAlign: captionAlign,
            widthValue: widthValue
        }, caption));
    });
const codeInputConfig = {
    name: 'CodeInput',
    tag: 'div',
    layout: codeInputRoot,
    base: _CodeInputstyles.base,
    variations: {
        view: {
            css: _base.base
        },
        size: {
            css: _base1.base
        },
        disabled: {
            css: _base2.base,
            attrs: true
        }
    },
    defaults: {
        size: 'm',
        view: 'default'
    }
};
