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 _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);
}
import React, { forwardRef, Fragment, useCallback, useRef, useState } from "react";
import cls from "classnames";
import { useDidMountEffect } from "../../hooks";
import { getSizeValueFromProp } from "../../utils";
import { BACKSPACE_KEY, FORBIDDEN_KEYS, ONLY_DIGITS_PATTERN } from "../../utils/constants";
import { useCodeHook } from "../../hooks";
import { getCodeValue, getFieldPattern, getPlaceholderValue, handleCodeError, handleItemError } from "./utils";
import { classes } from "./CodeInput.tokens";
import { base, CaptionWrapper, CodeGroup, CodeWrapper, ItemInput, Separator, ItemWrapper, ItemCircle } from "./CodeInput.styles";
import { base as viewCSS } from "./variations/_view/base";
import { base as sizeCSS } from "./variations/_size/base";
import { base as disabledCSS } from "./variations/_disabled/base";
export var codeInputRoot = function codeInputRoot(Root) {
    return /*#__PURE__*/ forwardRef(function(_0, _1) {
        var _ref = [
            _0,
            _1
        ], _ref1 = _to_array(_ref), _ref2 = _ref1[0], _rest = _ref1.slice(1), className = _ref2.className, 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, view = _ref2.view, size = _ref2.size, hidden = _ref2.hidden, disabled = _ref2.disabled, isError = _ref2.isError, _ref_allowedSymbols = _ref2.allowedSymbols, allowedSymbols = _ref_allowedSymbols === void 0 ? 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",
            "placeholder",
            "autoFocus",
            "codeLength",
            "caption",
            "captionAlign",
            "width",
            "view",
            "size",
            "hidden",
            "disabled",
            "isError",
            "allowedSymbols",
            "itemErrorBehavior",
            "codeErrorBehavior",
            "autoComplete",
            "setIsError",
            "onChange",
            "onFullCodeEnter"
        ]), _rest1 = _sliced_to_array(_rest, 1), ref = _rest1[0];
        var _useState = _sliced_to_array(useState(getCodeValue(codeLength, '')), 2), code = _useState[0], setCode = _useState[1];
        var _useState1 = _sliced_to_array(useState(code.join('')), 2), originalValue = _useState1[0], setOriginalValue = _useState1[1];
        var inputRefs = useRef([]);
        var inputContainerRef = useRef(null);
        var captionRef = useRef(null);
        var fieldPattern = getFieldPattern(allowedSymbols);
        var placeholderValue = getPlaceholderValue(codeLength, placeholder);
        var parts = codeLength === 6 ? 2 : 1;
        var widthValue = width ? getSizeValueFromProp(width, 'rem') : undefined;
        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 handleClick = function handleClick() {
            if (disabled) {
                return;
            }
            var lastActiveIndex = getLastActiveIndex();
            if (inputRefs.current[lastActiveIndex]) {
                inputRefs.current[lastActiveIndex].focus();
            }
        };
        var handleOnKeyDown = function handleOnKeyDown(event, index, type) {
            if (disabled) {
                return;
            }
            var key = event.key;
            if (FORBIDDEN_KEYS.includes(key)) {
                event.preventDefault();
                return;
            }
            if (key === BACKSPACE_KEY) {
                if (index > 0 && code[index] === '') {
                    var _inputRefs_current_;
                    (_inputRefs_current_ = inputRefs.current[index - 1]) === null || _inputRefs_current_ === void 0 ? void 0 : _inputRefs_current_.focus();
                }
            }
            if (type === 'circle') {
                var _inputRefs_current_index;
                handleAddSymbol(key, index);
                (_inputRefs_current_index = inputRefs.current[index]) === null || _inputRefs_current_index === void 0 ? void 0 : _inputRefs_current_index.focus();
            }
        };
        var codeSetter = function codeSetter(newCode) {
            setCode(newCode);
            setOriginalValue(newCode.join(''));
            if (onChange) {
                onChange(newCode.join(''));
            }
        };
        var handleChange = function handleChange(event, 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);
            handleAddSymbol(symbol, index);
        };
        var handleAddSymbol = function handleAddSymbol(symbol, index) {
            var _inputRefs_current_index;
            var newCode = _to_consumable_array(code);
            (_inputRefs_current_index = inputRefs.current[index]) === null || _inputRefs_current_index === void 0 ? void 0 : _inputRefs_current_index.classList.remove(classes.itemError);
            if (isError) {
                var _captionRef_current;
                (_captionRef_current = captionRef.current) === null || _captionRef_current === void 0 ? void 0 : _captionRef_current.classList.remove(classes.captionError);
                if (codeErrorBehavior === 'keep') {
                    var _inputContainerRef_current;
                    (_inputContainerRef_current = inputContainerRef.current) === null || _inputContainerRef_current === void 0 ? void 0 : _inputContainerRef_current.classList.remove(classes.codeError, classes.codeErrorAnimation);
                }
                if (setIsError) {
                    setIsError(false);
                }
            }
            if (!fieldPattern) {
                newCode[index] = symbol;
                codeSetter(newCode);
                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 (!symbol) {
                newCode[index] = '';
                codeSetter(newCode);
                return;
            }
            if (fieldPattern.test(symbol)) {
                newCode[index] = symbol.charAt(symbol.length - 1);
                codeSetter(newCode);
                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 {
                newCode[index] = symbol.charAt(symbol.length - 1);
                handleItemError({
                    currentSymbol: symbol,
                    itemErrorBehavior: itemErrorBehavior,
                    index: index,
                    newCode: newCode,
                    inputRefs: inputRefs,
                    inputContainerRef: inputContainerRef,
                    codeSetter: codeSetter
                });
            }
        };
        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 = useCallback(function(fullCode) {
            if (onFullCodeEnter) {
                onFullCodeEnter(fullCode);
            }
        }, []);
        useCodeHook({
            inputRefs: inputRefs,
            codeLength: codeLength,
            disabled: disabled,
            autoFocus: autoFocus,
            originalValue: originalValue,
            getLastActiveIndex: getLastActiveIndex,
            handleFullCodeEnter: handleFullCodeEnter
        });
        useDidMountEffect(function() {
            if (isError) {
                handleCodeError({
                    codeLength: codeLength,
                    codeErrorBehavior: codeErrorBehavior,
                    currentCode: code,
                    inputRefs: inputRefs,
                    inputContainerRef: inputContainerRef,
                    captionRef: captionRef,
                    setCode: setCode,
                    codeSetter: codeSetter
                });
            }
        }, [
            isError
        ]);
        return /*#__PURE__*/ React.createElement(Root, _object_spread({
            ref: ref,
            view: view,
            size: size,
            disabled: disabled,
            onClick: handleClick,
            className: cls(className, _define_property({}, classes.captionAlignLeft, captionAlign === 'left'))
        }, rest), /*#__PURE__*/ React.createElement(CodeWrapper, {
            ref: inputContainerRef
        }, _to_consumable_array(Array(parts)).map(function(_, partIndex) {
            return /*#__PURE__*/ React.createElement(Fragment, {
                key: partIndex
            }, /*#__PURE__*/ React.createElement(CodeGroup, {
                role: "group"
            }, _to_consumable_array(Array(codeLength / parts)).map(function(_, i) {
                var inputCorrectIndex = i + codeLength / parts * partIndex;
                return /*#__PURE__*/ React.createElement(ItemWrapper, {
                    key: String(partIndex + i + partIndex * i)
                }, (!code[inputCorrectIndex] || Boolean(code[inputCorrectIndex]) && hidden) && /*#__PURE__*/ React.createElement(ItemCircle, {
                    role: "tab",
                    tabIndex: originalValue.length === inputCorrectIndex ? 0 : -1,
                    onKeyDown: function onKeyDown(e) {
                        handleOnKeyDown(e, inputCorrectIndex, 'circle');
                    },
                    className: cls([
                        Boolean(code[inputCorrectIndex]) && hidden ? classes.itemCirlceFilled : '',
                        "".concat(classes.itemCircle, "-").concat(inputCorrectIndex)
                    ])
                }), /*#__PURE__*/ React.createElement(ItemInput, _object_spread({
                    ref: function ref(element) {
                        inputRefs.current[inputCorrectIndex] = element;
                    },
                    className: cls(_define_property({}, classes.hoverEnabled, inputCorrectIndex >= originalValue.length)),
                    hide: hidden,
                    value: code[inputCorrectIndex] || '',
                    tabIndex: originalValue.length === inputCorrectIndex ? 0 : -1,
                    autoComplete: autoComplete,
                    onChange: function onChange(e) {
                        handleChange(e, inputCorrectIndex);
                    },
                    onKeyDown: function onKeyDown(e) {
                        handleOnKeyDown(e, inputCorrectIndex);
                    },
                    onPaste: handlePaste
                }, placeholderValue && {
                    placeholder: placeholderValue[inputCorrectIndex]
                })));
            })), partIndex !== parts - 1 && /*#__PURE__*/ React.createElement(Separator, null));
        })), caption && /*#__PURE__*/ React.createElement(CaptionWrapper, {
            ref: captionRef,
            captionAlign: captionAlign,
            widthValue: widthValue
        }, caption));
    });
};
export var codeInputConfig = {
    name: 'CodeInput',
    tag: 'div',
    layout: codeInputRoot,
    base: base,
    variations: {
        view: {
            css: viewCSS
        },
        size: {
            css: sizeCSS
        },
        disabled: {
            css: disabledCSS,
            attrs: true
        }
    },
    defaults: {
        size: 'm',
        view: 'default'
    }
};
