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, useEffect, useRef, useState } from "react";
import cls from "classnames";
import { useDidMountEffect } from "../../hooks";
import { getSizeValueFromProp } from "../../utils";
import { useCodeHook } from "../../hooks";
import { BACKSPACE_KEY, FORBIDDEN_KEYS, ONLY_DIGITS_PATTERN } from "./utils/constants";
import { getCodeValue, getFieldPattern, getPlaceholderValue, handleCodeError, handleItemError, isWebOTPSupported } from "./utils";
import { classes } from "./CodeField.tokens";
import { base, CaptionWrapper, CodeGroup, CodeWrapper, HiddenInput, ItemInput, Separator } from "./CodeField.styles";
import { base as viewCSS } from "./variations/_view/base";
import { base as sizeCSS } from "./variations/_size/base";
import { base as shapeCSS } from "./variations/_shape/base";
import { base as disabledCSS } from "./variations/_disabled/base";
import { useWebOTP } from "./hooks/useWebOTP";
export var codeFieldRoot = function codeFieldRoot(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, 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 ? 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(useState(getCodeValue(codeLength, '')), 2), innerValue = _useState[0], setInnerValue = _useState[1];
        var code = typeof outerValue === 'string' ? getCodeValue(codeLength, outerValue) : innerValue;
        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 autocompleteRef = 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 isWebOTPEnabled = autoComplete === 'one-time-code' && !disabled && 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(getCodeValue(codeLength, originalCode));
            setOriginalValue(originalCode);
            if (onChange) {
                onChange(originalCode);
            }
        };
        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 (FORBIDDEN_KEYS.includes(key)) {
                event.preventDefault();
                return;
            }
            if (key === 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(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(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 (!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);
                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 = 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,
                    setInnerValue: setInnerValue,
                    codeSetter: codeSetter
                });
            }
        }, [
            isError
        ]);
        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.createElement(React.Fragment, null, /*#__PURE__*/ React.createElement(Root, _object_spread({
            ref: ref,
            view: view,
            size: size,
            shape: shape,
            disabled: disabled,
            onClick: handleClick,
            className: cls(className, _define_property({}, classes.captionAlignLeft, captionAlign === 'left'))
        }, !isWebOTPEnabled && _object_spread({}, 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(_item, i) {
                var inputCorrectIndex = i + codeLength / parts * partIndex;
                var _obj;
                return /*#__PURE__*/ React.createElement(ItemInput, _object_spread({
                    key: partIndex + i + partIndex * i,
                    ref: function ref(element) {
                        inputRefs.current[inputCorrectIndex] = element;
                    },
                    className: cls((_obj = {}, _define_property(_obj, classes.segmented, shape === 'segmented'), _define_property(_obj, 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.createElement(Separator, null));
        })), caption && /*#__PURE__*/ React.createElement(CaptionWrapper, {
            ref: captionRef,
            captionAlign: captionAlign,
            widthValue: widthValue
        }, caption), isWebOTPEnabled && /*#__PURE__*/ React.createElement(HiddenInput, _object_spread({
            ref: autocompleteRef,
            autoComplete: autoComplete,
            tabIndex: -1
        }, rest))));
    });
};
export var codeFieldConfig = {
    name: 'CodeField',
    tag: 'div',
    layout: codeFieldRoot,
    base: base,
    variations: {
        view: {
            css: viewCSS
        },
        size: {
            css: sizeCSS
        },
        shape: {
            css: shapeCSS
        },
        disabled: {
            css: disabledCSS,
            attrs: true
        }
    },
    defaults: {
        size: 'm',
        view: 'default',
        shape: 'default'
    }
};
