"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;
    }
});
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 _hooks1 = require("../../hooks");
const _constants = require("./utils/constants");
const _utils1 = require("./utils");
const _CodeFieldtokens = require("./CodeField.tokens");
const _CodeFieldstyles = require("./CodeField.styles");
const _base = require("./variations/_view/base");
const _base1 = require("./variations/_size/base");
const _base2 = require("./variations/_shape/base");
const _base3 = require("./variations/_disabled/base");
const _useWebOTP = require("./hooks/useWebOTP");
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 codeFieldRoot = (Root)=>/*#__PURE__*/ (0, _react.forwardRef)(({ className, value: outerValue, placeholder, autoFocus, codeLength = 6, caption, captionAlign = 'left', width, shape = 'default', view, size, disabled, isError, allowedSymbols = _constants.ONLY_DIGITS_PATTERN, itemErrorBehavior = 'remove-symbol', codeErrorBehavior = 'remove-code', autoComplete = 'one-time-code', inputMode, setIsError, onChange, onFullCodeEnter, ...rest }, ref)=>{
        const [innerValue, setInnerValue] = (0, _react.useState)((0, _utils1.getCodeValue)(codeLength, ''));
        const code = typeof outerValue === 'string' ? (0, _utils1.getCodeValue)(codeLength, outerValue) : innerValue;
        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 autocompleteRef = (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 isWebOTPEnabled = autoComplete === 'one-time-code' && !disabled && (0, _utils1.isWebOTPSupported)();
        const getLastActiveIndex = ()=>{
            if (code.length && code.length < codeLength) {
                return code.length;
            }
            const lastEmptyIndex = code.findIndex((digit)=>digit === '');
            return lastEmptyIndex >= 0 ? lastEmptyIndex : codeLength - 1;
        };
        const codeSetter = (newCode)=>{
            const 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,
            codeSetter,
            onFullCodeEnter
        });
        const handleClick = ()=>{
            if (disabled) {
                return;
            }
            const lastActiveIndex = getLastActiveIndex();
            if (inputRefs.current[lastActiveIndex]) {
                inputRefs.current[lastActiveIndex].focus();
            }
        };
        const handleOnKeyDown = (event, index)=>{
            if (disabled) {
                return;
            }
            const { key } = event;
            if (_constants.FORBIDDEN_KEYS.includes(key)) {
                event.preventDefault();
                return;
            }
            if (key === _constants.BACKSPACE_KEY) {
                if (index > 0) {
                    const newCode = [
                        ...code
                    ];
                    newCode[index] = '';
                    if (index >= codeLength - 1 && code[index]) {
                        codeSetter(newCode);
                        return;
                    }
                    if (!code[index]) {
                        newCode[index - 1] = '';
                        inputRefs.current[index - 1]?.focus();
                    }
                    inputRefs.current[index]?.classList.remove(_CodeFieldtokens.classes.itemError);
                    codeSetter(newCode);
                }
            }
        };
        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);
            const newCode = [
                ...code
            ];
            inputRefs.current[index]?.classList.remove(_CodeFieldtokens.classes.itemError);
            if (isError) {
                captionRef.current?.classList.remove(_CodeFieldtokens.classes.captionError);
                if (codeErrorBehavior === 'keep') {
                    inputContainerRef.current?.classList.remove(_CodeFieldtokens.classes.codeError, _CodeFieldtokens.classes.codeErrorAnimation);
                }
                if (setIsError) {
                    setIsError(false);
                }
            }
            if (!symbol) {
                return;
            }
            if (!fieldPattern) {
                newCode[index] = symbol;
                codeSetter(newCode);
                if (symbol && index < codeLength - 1) {
                    inputRefs.current[index + 1]?.focus();
                }
                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,
                    setInnerValue,
                    codeSetter,
                    onChange
                });
            }
        };
        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, _hooks1.useCodeHook)({
            inputRefs,
            codeLength,
            disabled,
            autoFocus,
            originalValue,
            getLastActiveIndex,
            handleFullCodeEnter
        });
        (0, _hooks.useDidMountEffect)(()=>{
            if (isError) {
                (0, _utils1.handleCodeError)({
                    codeLength,
                    codeErrorBehavior,
                    currentCode: code,
                    inputRefs,
                    inputContainerRef,
                    captionRef,
                    setInnerValue,
                    codeSetter
                });
            }
        }, [
            isError
        ]);
        (0, _react.useEffect)(()=>{
            if (disabled || !autocompleteRef.current) {
                return;
            }
            const autocompleteCode = autocompleteRef.current.value.split('');
            codeSetter(autocompleteCode);
        }, [
            autocompleteRef.current?.value,
            disabled
        ]);
        return /*#__PURE__*/ _react.default.createElement(_react.default.Fragment, null, /*#__PURE__*/ _react.default.createElement(Root, {
            ref: ref,
            view: view,
            size: size,
            shape: shape,
            disabled: disabled,
            onClick: handleClick,
            className: (0, _classnames.default)(className, {
                [_CodeFieldtokens.classes.captionAlignLeft]: captionAlign === 'left'
            }),
            ...!isWebOTPEnabled && {
                ...rest
            }
        }, /*#__PURE__*/ _react.default.createElement(_CodeFieldstyles.CodeWrapper, {
            ref: inputContainerRef
        }, [
            ...Array(parts)
        ].map((_, partIndex)=>/*#__PURE__*/ _react.default.createElement(_react.Fragment, {
                key: partIndex
            }, /*#__PURE__*/ _react.default.createElement(_CodeFieldstyles.CodeGroup, {
                role: "group"
            }, [
                ...Array(codeLength / parts)
            ].map((_item, i)=>{
                const inputCorrectIndex = i + codeLength / parts * partIndex;
                return /*#__PURE__*/ _react.default.createElement(_CodeFieldstyles.ItemInput, {
                    key: partIndex + i + partIndex * i,
                    ref: (element)=>{
                        inputRefs.current[inputCorrectIndex] = element;
                    },
                    className: (0, _classnames.default)({
                        [_CodeFieldtokens.classes.segmented]: shape === 'segmented',
                        [_CodeFieldtokens.classes.hoverEnabled]: !disabled && inputCorrectIndex >= originalValue.length
                    }),
                    inputMode: inputMode,
                    value: code[inputCorrectIndex] || '',
                    onChange: (e)=>{
                        handleChange(e, inputCorrectIndex);
                    },
                    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, {
            ref: autocompleteRef,
            autoComplete: autoComplete,
            tabIndex: -1,
            ...rest
        })));
    });
const 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'
    }
};
