"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 codeFieldConfig () {
        return codeFieldConfig;
    },
    get codeFieldRoot () {
        return codeFieldRoot;
    }
});
var _react = /*#__PURE__*/ _interop_require_wildcard(require("react"));
var _classnames = /*#__PURE__*/ _interop_require_default(require("classnames"));
var _hooks = require("../../hooks");
var _utils = require("../../utils");
var _hooks1 = require("../../hooks");
var _constants = require("./utils/constants");
var _utils1 = require("./utils");
var _CodeFieldtokens = require("./CodeField.tokens");
var _CodeFieldstyles = require("./CodeField.styles");
var _base = require("./variations/_view/base");
var _base1 = require("./variations/_size/base");
var _base2 = require("./variations/_shape/base");
var _base3 = require("./variations/_disabled/base");
var _useWebOTP = require("./hooks/useWebOTP");
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 _array_without_holes(arr) {
    if (Array.isArray(arr)) return _array_like_to_array(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 _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;
}
function _iterable_to_array(iter) {
    if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter);
}
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 _non_iterable_spread() {
    throw new TypeError("Invalid attempt to spread 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 _to_array(arr) {
    return _array_with_holes(arr) || _iterable_to_array(arr) || _unsupported_iterable_to_array(arr) || _non_iterable_rest();
}
function _to_consumable_array(arr) {
    return _array_without_holes(arr) || _iterable_to_array(arr) || _unsupported_iterable_to_array(arr) || _non_iterable_spread();
}
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);
}
var codeFieldRoot = function codeFieldRoot(Root) {
    return /*#__PURE__*/ (0, _react.forwardRef)(function(_0, _1) {
        var _ref = [
            _0,
            _1
        ], _ref1 = _to_array(_ref), _ref2 = _ref1[0], _rest = _ref1.slice(1), className = _ref2.className, outerValue = _ref2.value, placeholder = _ref2.placeholder, autoFocus = _ref2.autoFocus, _ref_codeLength = _ref2.codeLength, codeLength = _ref_codeLength === void 0 ? 6 : _ref_codeLength, caption = _ref2.caption, _ref_captionAlign = _ref2.captionAlign, captionAlign = _ref_captionAlign === void 0 ? 'left' : _ref_captionAlign, width = _ref2.width, _ref_shape = _ref2.shape, shape = _ref_shape === void 0 ? 'default' : _ref_shape, view = _ref2.view, size = _ref2.size, disabled = _ref2.disabled, isError = _ref2.isError, _ref_allowedSymbols = _ref2.allowedSymbols, allowedSymbols = _ref_allowedSymbols === void 0 ? _constants.ONLY_DIGITS_PATTERN : _ref_allowedSymbols, _ref_itemErrorBehavior = _ref2.itemErrorBehavior, itemErrorBehavior = _ref_itemErrorBehavior === void 0 ? 'remove-symbol' : _ref_itemErrorBehavior, _ref_codeErrorBehavior = _ref2.codeErrorBehavior, codeErrorBehavior = _ref_codeErrorBehavior === void 0 ? 'remove-code' : _ref_codeErrorBehavior, _ref_autoComplete = _ref2.autoComplete, autoComplete = _ref_autoComplete === void 0 ? 'one-time-code' : _ref_autoComplete, setIsError = _ref2.setIsError, onChange = _ref2.onChange, onFullCodeEnter = _ref2.onFullCodeEnter, rest = _object_without_properties(_ref2, [
            "className",
            "value",
            "placeholder",
            "autoFocus",
            "codeLength",
            "caption",
            "captionAlign",
            "width",
            "shape",
            "view",
            "size",
            "disabled",
            "isError",
            "allowedSymbols",
            "itemErrorBehavior",
            "codeErrorBehavior",
            "autoComplete",
            "setIsError",
            "onChange",
            "onFullCodeEnter"
        ]), _rest1 = _sliced_to_array(_rest, 1), ref = _rest1[0];
        var _autocompleteRef_current;
        var _useState = _sliced_to_array((0, _react.useState)((0, _utils1.getCodeValue)(codeLength, '')), 2), innerValue = _useState[0], setInnerValue = _useState[1];
        var code = typeof outerValue === 'string' ? (0, _utils1.getCodeValue)(codeLength, outerValue) : innerValue;
        var _useState1 = _sliced_to_array((0, _react.useState)(code.join('')), 2), originalValue = _useState1[0], setOriginalValue = _useState1[1];
        var inputRefs = (0, _react.useRef)([]);
        var inputContainerRef = (0, _react.useRef)(null);
        var captionRef = (0, _react.useRef)(null);
        var autocompleteRef = (0, _react.useRef)(null);
        var fieldPattern = (0, _utils1.getFieldPattern)(allowedSymbols);
        var placeholderValue = (0, _utils1.getPlaceholderValue)(codeLength, placeholder);
        var parts = codeLength === 6 ? 2 : 1;
        var widthValue = width ? (0, _utils.getSizeValueFromProp)(width, 'rem') : undefined;
        var isWebOTPEnabled = autoComplete === 'one-time-code' && !disabled && (0, _utils1.isWebOTPSupported)();
        var getLastActiveIndex = function getLastActiveIndex() {
            if (code.length && code.length < codeLength) {
                return code.length;
            }
            var lastEmptyIndex = code.findIndex(function(digit) {
                return digit === '';
            });
            return lastEmptyIndex >= 0 ? lastEmptyIndex : codeLength - 1;
        };
        var codeSetter = function codeSetter(newCode) {
            var originalCode = newCode.join('');
            setInnerValue((0, _utils1.getCodeValue)(codeLength, originalCode));
            setOriginalValue(originalCode);
            if (onChange) {
                onChange(originalCode);
            }
        };
        (0, _useWebOTP.useWebOTP)({
            codeString: originalValue,
            enableSMSAutoRead: autoComplete === 'one-time-code',
            disabled: Boolean(disabled),
            codeLength: codeLength,
            codeSetter: codeSetter,
            onFullCodeEnter: onFullCodeEnter
        });
        var handleClick = function handleClick() {
            if (disabled) {
                return;
            }
            var lastActiveIndex = getLastActiveIndex();
            if (inputRefs.current[lastActiveIndex]) {
                inputRefs.current[lastActiveIndex].focus();
            }
        };
        var handleOnKeyDown = function handleOnKeyDown(event, index) {
            if (disabled) {
                return;
            }
            var key = event.key;
            if (_constants.FORBIDDEN_KEYS.includes(key)) {
                event.preventDefault();
                return;
            }
            if (key === _constants.BACKSPACE_KEY) {
                if (index > 0) {
                    var _inputRefs_current_index;
                    var newCode = _to_consumable_array(code);
                    newCode[index] = '';
                    if (index >= codeLength - 1 && code[index]) {
                        codeSetter(newCode);
                        return;
                    }
                    if (!code[index]) {
                        var _inputRefs_current_;
                        newCode[index - 1] = '';
                        (_inputRefs_current_ = inputRefs.current[index - 1]) === null || _inputRefs_current_ === void 0 ? void 0 : _inputRefs_current_.focus();
                    }
                    (_inputRefs_current_index = inputRefs.current[index]) === null || _inputRefs_current_index === void 0 ? void 0 : _inputRefs_current_index.classList.remove(_CodeFieldtokens.classes.itemError);
                    codeSetter(newCode);
                }
            }
        };
        var handleChange = function handleChange(event, index) {
            var _inputRefs_current_index;
            if (disabled) {
                return;
            }
            var rawSymbol = event.currentTarget.value;
            // На мобильных устройствах вставка вызывает onChange по 1 символу
            if (rawSymbol.length > 1) {
                var _inputRefs_current_activeIndex;
                var newCode = _to_consumable_array(code);
                var pastedData = (fieldPattern ? rawSymbol.split('').map(function(symb) {
                    var _symb_match;
                    return ((_symb_match = symb.match(fieldPattern)) === null || _symb_match === void 0 ? void 0 : _symb_match[0]) || '';
                }).filter(Boolean) : rawSymbol.split('')).slice(0, codeLength - index);
                pastedData.forEach(function(element, i) {
                    newCode[index + i] = element;
                });
                var activeIndex = Math.min(index + pastedData.length, codeLength - 1);
                (_inputRefs_current_activeIndex = inputRefs.current[activeIndex]) === null || _inputRefs_current_activeIndex === void 0 ? void 0 : _inputRefs_current_activeIndex.focus();
                codeSetter(newCode);
                return;
            }
            var symbol = rawSymbol.charAt(rawSymbol.length - 1);
            var newCode1 = _to_consumable_array(code);
            (_inputRefs_current_index = inputRefs.current[index]) === null || _inputRefs_current_index === void 0 ? void 0 : _inputRefs_current_index.classList.remove(_CodeFieldtokens.classes.itemError);
            if (isError) {
                var _captionRef_current;
                (_captionRef_current = captionRef.current) === null || _captionRef_current === void 0 ? void 0 : _captionRef_current.classList.remove(_CodeFieldtokens.classes.captionError);
                if (codeErrorBehavior === 'keep') {
                    var _inputContainerRef_current;
                    (_inputContainerRef_current = inputContainerRef.current) === null || _inputContainerRef_current === void 0 ? void 0 : _inputContainerRef_current.classList.remove(_CodeFieldtokens.classes.codeError, _CodeFieldtokens.classes.codeErrorAnimation);
                }
                if (setIsError) {
                    setIsError(false);
                }
            }
            if (!symbol) {
                return;
            }
            if (!fieldPattern) {
                newCode1[index] = symbol;
                codeSetter(newCode1);
                if (symbol && index < codeLength - 1) {
                    var _inputRefs_current_;
                    (_inputRefs_current_ = inputRefs.current[index + 1]) === null || _inputRefs_current_ === void 0 ? void 0 : _inputRefs_current_.focus();
                }
                return;
            }
            if (fieldPattern.test(symbol)) {
                newCode1[index] = symbol.charAt(symbol.length - 1);
                codeSetter(newCode1);
                if (index < codeLength - 1) {
                    var _inputRefs_current_1;
                    (_inputRefs_current_1 = inputRefs.current[index + 1]) === null || _inputRefs_current_1 === void 0 ? void 0 : _inputRefs_current_1.focus();
                }
            } else {
                newCode1[index] = symbol.charAt(symbol.length - 1);
                (0, _utils1.handleItemError)({
                    currentSymbol: symbol,
                    itemErrorBehavior: itemErrorBehavior,
                    index: index,
                    newCode: newCode1,
                    inputRefs: inputRefs,
                    setInnerValue: setInnerValue,
                    codeSetter: codeSetter,
                    onChange: onChange
                });
            }
        };
        var handlePaste = function handlePaste(event) {
            var _inputRefs_current_activeIndex;
            var newCode = _to_consumable_array(code);
            if (disabled) {
                return;
            }
            event.preventDefault();
            var rawData = event.clipboardData.getData('text/plain');
            var pastedData = (fieldPattern ? rawData.split('').map(function(symb) {
                var _symb_match;
                return ((_symb_match = symb.match(fieldPattern)) === null || _symb_match === void 0 ? void 0 : _symb_match[0]) || '';
            }).filter(Boolean) || [] : rawData.split('')).slice(0, codeLength);
            pastedData.forEach(function(element, index) {
                newCode[index] = element;
            });
            var activeIndex = Math.min(pastedData.length, codeLength - 1);
            (_inputRefs_current_activeIndex = inputRefs.current[activeIndex]) === null || _inputRefs_current_activeIndex === void 0 ? void 0 : _inputRefs_current_activeIndex.focus();
            codeSetter(newCode);
        };
        var handleFullCodeEnter = (0, _react.useCallback)(function(fullCode) {
            if (onFullCodeEnter) {
                onFullCodeEnter(fullCode);
            }
        }, []);
        (0, _hooks1.useCodeHook)({
            inputRefs: inputRefs,
            codeLength: codeLength,
            disabled: disabled,
            autoFocus: autoFocus,
            originalValue: originalValue,
            getLastActiveIndex: getLastActiveIndex,
            handleFullCodeEnter: handleFullCodeEnter
        });
        (0, _hooks.useDidMountEffect)(function() {
            if (isError) {
                (0, _utils1.handleCodeError)({
                    codeLength: codeLength,
                    codeErrorBehavior: codeErrorBehavior,
                    currentCode: code,
                    inputRefs: inputRefs,
                    inputContainerRef: inputContainerRef,
                    captionRef: captionRef,
                    setInnerValue: setInnerValue,
                    codeSetter: codeSetter
                });
            }
        }, [
            isError
        ]);
        (0, _react.useEffect)(function() {
            if (disabled || !autocompleteRef.current) {
                return;
            }
            var autocompleteCode = autocompleteRef.current.value.split('');
            codeSetter(autocompleteCode);
        }, [
            (_autocompleteRef_current = autocompleteRef.current) === null || _autocompleteRef_current === void 0 ? void 0 : _autocompleteRef_current.value,
            disabled
        ]);
        return /*#__PURE__*/ _react.default.createElement(_react.default.Fragment, null, /*#__PURE__*/ _react.default.createElement(Root, _object_spread({
            ref: ref,
            view: view,
            size: size,
            shape: shape,
            disabled: disabled,
            onClick: handleClick,
            className: (0, _classnames.default)(className, _define_property({}, _CodeFieldtokens.classes.captionAlignLeft, captionAlign === 'left'))
        }, !isWebOTPEnabled && _object_spread({}, rest)), /*#__PURE__*/ _react.default.createElement(_CodeFieldstyles.CodeWrapper, {
            ref: inputContainerRef
        }, _to_consumable_array(Array(parts)).map(function(_, partIndex) {
            return /*#__PURE__*/ _react.default.createElement(_react.Fragment, {
                key: partIndex
            }, /*#__PURE__*/ _react.default.createElement(_CodeFieldstyles.CodeGroup, {
                role: "group"
            }, _to_consumable_array(Array(codeLength / parts)).map(function(_item, i) {
                var inputCorrectIndex = i + codeLength / parts * partIndex;
                var _obj;
                return /*#__PURE__*/ _react.default.createElement(_CodeFieldstyles.ItemInput, _object_spread({
                    key: partIndex + i + partIndex * i,
                    ref: function ref(element) {
                        inputRefs.current[inputCorrectIndex] = element;
                    },
                    className: (0, _classnames.default)((_obj = {}, _define_property(_obj, _CodeFieldtokens.classes.segmented, shape === 'segmented'), _define_property(_obj, _CodeFieldtokens.classes.hoverEnabled, !disabled && inputCorrectIndex >= originalValue.length), _obj)),
                    value: code[inputCorrectIndex] || '',
                    onChange: function onChange(e) {
                        handleChange(e, inputCorrectIndex);
                    },
                    onKeyDown: function onKeyDown(e) {
                        handleOnKeyDown(e, inputCorrectIndex);
                    },
                    onPaste: handlePaste,
                    tabIndex: !disabled && originalValue.length === inputCorrectIndex ? 0 : -1
                }, placeholderValue && {
                    placeholder: placeholderValue[inputCorrectIndex]
                }));
            })), partIndex !== parts - 1 && /*#__PURE__*/ _react.default.createElement(_CodeFieldstyles.Separator, null));
        })), caption && /*#__PURE__*/ _react.default.createElement(_CodeFieldstyles.CaptionWrapper, {
            ref: captionRef,
            captionAlign: captionAlign,
            widthValue: widthValue
        }, caption), isWebOTPEnabled && /*#__PURE__*/ _react.default.createElement(_CodeFieldstyles.HiddenInput, _object_spread({
            ref: autocompleteRef,
            autoComplete: autoComplete,
            tabIndex: -1
        }, rest))));
    });
};
var codeFieldConfig = {
    name: 'CodeField',
    tag: 'div',
    layout: codeFieldRoot,
    base: _CodeFieldstyles.base,
    variations: {
        view: {
            css: _base.base
        },
        size: {
            css: _base1.base
        },
        shape: {
            css: _base2.base
        },
        disabled: {
            css: _base3.base,
            attrs: true
        }
    },
    defaults: {
        size: 'm',
        view: 'default',
        shape: 'default'
    }
};
