"use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

var _chunkQ4PPWLDCcjs = require('./chunk-Q4PPWLDC.cjs');


var _chunkAEJ7VTL4cjs = require('./chunk-AEJ7VTL4.cjs');



var _chunkZ6EUSUADcjs = require('./chunk-Z6EUSUAD.cjs');

// src/components/CodeInput/CodeInput.tsx
var _styled = require('@emotion/styled'); var _styled2 = _interopRequireDefault(_styled);
var _lodashes = require('lodash-es');
var _nanoid = require('nanoid');
var _react = require('react');
var _reactdevicedetect = require('react-device-detect');
var _jsxruntime = require('@emotion/react/jsx-runtime');
function codeFromInputState(inputState) {
  return Object.values(inputState).map((input) => input.value).join("");
}
function getRef(key, refsObj) {
  if (key && refsObj && typeof refsObj === "object" && refsObj.current) {
    const ref = refsObj.current[key];
    if (ref && typeof ref === "object" && ref.current && ref.current instanceof HTMLInputElement) {
      return ref.current;
    }
  }
  return null;
}
function CodeInput({
  codeLength = 8,
  onChange,
  onSubmit,
  inputCSS,
  autoFocus = true,
  onBlur
}) {
  const componentId = _react.useRef.call(void 0, _nanoid.nanoid.call(void 0, 5));
  const inputRefs = _react.useRef.call(void 0, {});
  const autofillValuesRef = _react.useRef.call(void 0, "");
  const getInputId = _react.useCallback.call(void 0, (index) => {
    const idPrefix = `two-factor-input-${componentId.current}-`;
    return `${idPrefix}-${index}`;
  }, []);
  function getInputIndex(id) {
    return Number.parseInt(id.charAt(id.length - 1), 10);
  }
  const firstFieldRefCb = _react.useCallback.call(void 0, 
    (ref) => {
      if (ref) {
        inputRefs.current[ref.id] = _react.createRef.call(void 0, );
        inputRefs.current[ref.id].current = ref;
        if (ref.id === getInputId(0) && autoFocus) {
          ref.focus();
        }
      }
    },
    [getInputId, autoFocus]
  );
  const [inputState, setInputState] = _react.useState.call(void 0, 
    Array(codeLength).fill(0).reduce((acc, _, i) => {
      return _chunkZ6EUSUADcjs.__spreadProps.call(void 0, _chunkZ6EUSUADcjs.__spreadValues.call(void 0, {}, acc), {
        [getInputId(i)]: {
          value: ""
        }
      });
    }, {})
  );
  const onKeyDown = _react.useCallback.call(void 0, 
    (event, inputId) => {
      const handleKeys = /* @__PURE__ */ new Set([
        "0",
        "1",
        "2",
        "3",
        "4",
        "5",
        "6",
        "7",
        "8",
        "9",
        "Enter",
        "Escape",
        "Backspace",
        "Delete",
        "ArrowLeft",
        "ArrowRight"
      ]);
      if (["e", "E", "+", "-", "."].includes(event.key)) {
        event.preventDefault();
        return;
      }
      if (!handleKeys.has(event.key)) {
        return;
      }
      let replaceEntireState = false;
      const currentInputIndex = getInputIndex(inputId);
      const isFirstInput = currentInputIndex === 0;
      const isLastInput = currentInputIndex === codeLength - 1;
      const nextInputIndex = isLastInput ? void 0 : currentInputIndex + 1;
      const prevInputIndex = isFirstInput ? void 0 : currentInputIndex - 1;
      const nextInputId = _lodashes.isNumber.call(void 0, nextInputIndex) ? getInputId(nextInputIndex) : void 0;
      const prevInputId = _lodashes.isNumber.call(void 0, prevInputIndex) ? getInputId(prevInputIndex) : void 0;
      const nextInput = nextInputId ? inputState[nextInputId] : void 0;
      const prevInput = prevInputId ? inputState[prevInputId] : void 0;
      const currentInputRef = getRef(inputId, inputRefs);
      const nextInputRef = getRef(nextInputId, inputRefs);
      const prevInputRef = getRef(prevInputId, inputRefs);
      const firstInputRef = getRef(getInputId(0), inputRefs);
      const lastInputRef = getRef(getInputId(codeLength - 1), inputRefs);
      if (event.key === "ArrowLeft") {
        if (firstInputRef && (event.metaKey || event.ctrlKey || event.altKey)) {
          firstInputRef.focus();
          return;
        }
        if (prevInput && prevInputRef) {
          prevInputRef.focus();
          prevInputRef.select();
        }
        return;
      }
      if (event.key === "ArrowRight") {
        if (lastInputRef && (event.metaKey || event.ctrlKey || event.altKey)) {
          lastInputRef.focus();
          return;
        }
        if (nextInput && nextInputRef) {
          nextInputRef.focus();
          nextInputRef.select();
        }
        return;
      }
      if (event.key === "Enter" && onSubmit) {
        const code2 = codeFromInputState(inputState);
        onSubmit(code2);
        return;
      }
      if (event.key === "Escape" && currentInputRef) {
        currentInputRef.blur();
        return;
      }
      if (event.key === "Backspace" && (event.metaKey || event.ctrlKey || event.altKey)) {
        replaceEntireState = _chunkZ6EUSUADcjs.__spreadValues.call(void 0, {}, inputState);
        Object.keys(replaceEntireState).forEach((inputId2) => {
          const newState2 = replaceEntireState;
          newState2[inputId2] = _chunkZ6EUSUADcjs.__spreadProps.call(void 0, _chunkZ6EUSUADcjs.__spreadValues.call(void 0, {}, newState2[inputId2]), {
            value: ""
          });
        });
      }
      let value = event.key;
      if (event.key === "Backspace" && !event.metaKey && !event.ctrlKey && !event.altKey) {
        value = "";
        if (!isFirstInput && prevInput && prevInputRef) {
          prevInputRef.focus();
        }
      } else if (event.key === "Delete") {
        value = "";
        if (!isLastInput && nextInput && nextInputRef) {
          nextInputRef.focus();
        }
      } else if (replaceEntireState) {
        const lastInputWithValue = Object.entries(replaceEntireState).reverse().find(([, { value: value2 }]) => value2 !== "");
        if (lastInputWithValue) {
          const inputId2 = lastInputWithValue[0];
          const inputRef = getRef(inputId2, inputRefs);
          inputRef == null ? void 0 : inputRef.focus();
          inputRef == null ? void 0 : inputRef.select();
        } else if (firstInputRef) {
          firstInputRef.focus();
        }
      } else if (isLastInput) {
      } else if (nextInput && nextInputRef) {
        nextInputRef.focus();
        nextInputRef.select();
      }
      const newState = replaceEntireState ? replaceEntireState : _chunkZ6EUSUADcjs.__spreadProps.call(void 0, _chunkZ6EUSUADcjs.__spreadValues.call(void 0, {}, inputState), {
        [inputId]: { value }
      });
      const code = codeFromInputState(newState);
      if (onChange) {
        onChange(code);
      }
      setInputState(newState);
    },
    [onChange, setInputState, onSubmit, getInputId, inputState, codeLength]
  );
  const onPasteCb = _react.useCallback.call(void 0, 
    (event) => {
      event.preventDefault();
      const rawText = event.clipboardData.getData("text");
      const text = rawText == null ? void 0 : rawText.replace(/[\s.]/g, "");
      if (!text || Number.isNaN(Number.parseInt(text))) {
        return;
      }
      const inputValues = text.split("");
      const newState = _chunkZ6EUSUADcjs.__spreadValues.call(void 0, {}, inputState);
      inputValues.forEach((value, i) => {
        const inputId = getInputId(i);
        newState[inputId] = _chunkZ6EUSUADcjs.__spreadProps.call(void 0, _chunkZ6EUSUADcjs.__spreadValues.call(void 0, {}, newState[inputId]), {
          value
        });
      });
      const firstInputRef = getRef(getInputId(0), inputRefs);
      const lastInputWithValue = Object.entries(newState).reverse().find(([, { value }]) => value !== "");
      if (lastInputWithValue) {
        const inputId = lastInputWithValue[0];
        const inputRef = getRef(inputId, inputRefs);
        inputRef == null ? void 0 : inputRef.focus();
        inputRef == null ? void 0 : inputRef.select();
      } else if (firstInputRef) {
        firstInputRef.focus();
      }
      const code = codeFromInputState(newState);
      if (onChange) {
        onChange(code);
      }
      setInputState(newState);
    },
    [getInputId, inputState, onChange, setInputState]
  );
  const onBlurCb = _react.useCallback.call(void 0, () => {
    setTimeout(() => {
      let hasCodeFocused = false;
      if (inputRefs.current) {
        Object.values(inputRefs.current).forEach((ref) => {
          if (ref && ref.current && ref.current === document.activeElement) {
            hasCodeFocused = true;
          }
        });
        if (!hasCodeFocused && onBlur) {
          onBlur();
        }
      }
    }, 0);
  }, [onBlur]);
  const inputsPerGroup = Math.ceil(codeLength / 2);
  const inputs = [];
  for (let i = 0; i < codeLength; i += 1) {
    const inputId = getInputId(i);
    inputs.push(
      /* @__PURE__ */ _jsxruntime.jsx.call(void 0, 
        _chunkQ4PPWLDCcjs.SingleCodeInput,
        {
          value: inputState[inputId].value,
          id: inputId,
          inputRef: firstFieldRefCb,
          onPaste: onPasteCb,
          onKeyDown: (event) => onKeyDown(event, inputId),
          onChange: (event) => {
            if (_reactdevicedetect.isMobileSafari && event.nativeEvent instanceof CustomEvent) {
              autofillValuesRef.current += event.target.value;
              if (autofillValuesRef.current.length === codeLength) {
                const newState = Array(codeLength).fill(0).reduce((acc, _, i2) => {
                  return _chunkZ6EUSUADcjs.__spreadProps.call(void 0, _chunkZ6EUSUADcjs.__spreadValues.call(void 0, {}, acc), {
                    [getInputId(i2)]: {
                      value: autofillValuesRef.current[i2]
                    }
                  });
                }, {});
                setInputState(newState);
                if (onSubmit) {
                  onSubmit(autofillValuesRef.current);
                }
                autofillValuesRef.current = "";
              }
            } else if (_reactdevicedetect.isMobile && _reactdevicedetect.isChrome && event.target.value.length === codeLength) {
              const newState = Array(codeLength).fill(0).reduce((acc, _, i2) => {
                return _chunkZ6EUSUADcjs.__spreadProps.call(void 0, _chunkZ6EUSUADcjs.__spreadValues.call(void 0, {}, acc), {
                  [getInputId(i2)]: {
                    value: event.target.value[i2]
                  }
                });
              }, {});
              setInputState(newState);
              if (onSubmit) {
                onSubmit(event.target.value);
              }
            }
          },
          type: "number",
          ariaLabel: `Code input ${i + 1} of ${codeLength}`,
          cssProp: inputCSS,
          onBlur: onBlurCb,
          width: `${(100 / inputsPerGroup).toFixed(2)}%`,
          max: 9
        },
        inputId
      )
    );
  }
  return /* @__PURE__ */ _jsxruntime.jsxs.call(void 0, StyledCodeInput, { children: [
    /* @__PURE__ */ _jsxruntime.jsx.call(void 0, CodeInputGroup, { children: inputs.slice(0, inputsPerGroup) }),
    /* @__PURE__ */ _jsxruntime.jsx.call(void 0, CodeInputGroupSeparator, {}),
    /* @__PURE__ */ _jsxruntime.jsx.call(void 0, CodeInputGroup, { children: inputs.slice(inputsPerGroup, inputs.length) })
  ] });
}
var StyledCodeInput = _styled2.default.div`
  display: inline-flex;
  flex-direction: row;
  justify-content: space-between;
  align-items: center;
  flex-wrap: wrap;
`;
var separatorWidth = 12;
var separatorMargin = 8;
var CodeInputGroup = _styled2.default.div`
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  align-items: center;
  flex-wrap: wrap;
  width: calc(50% - ${(separatorWidth + separatorMargin * 2) / 2}px);
`;
var CodeInputGroupSeparator = _styled2.default.div`
  width: ${separatorWidth}px;
  height: 4px;
  background-color: ${_chunkAEJ7VTL4cjs.textInputBorderColor};
  border-radius: 2px;
  margin: 0 ${separatorMargin}px;
`;




exports.CodeInput = CodeInput; exports.StyledCodeInput = StyledCodeInput;
