function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread(); }
function _nonIterableSpread() { 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 _iterableToArray(iter) { if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter); }
function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) return _arrayLikeToArray(arr); }
function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); }
function _nonIterableRest() { 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 _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(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(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }
function _arrayLikeToArray(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 _iterableToArrayLimit(r, l) { var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (null != t) { var e, n, i, u, a = [], f = !0, o = !1; try { if (i = (t = t.call(r)).next, 0 === l) { if (Object(t) !== t) return; f = !1; } else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0); } catch (r) { o = !0, n = r; } finally { try { if (!f && null != t.return && (u = t.return(), Object(u) !== u)) return; } finally { if (o) throw n; } } return a; } }
function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }
/**
 * 验证码输入页面（对应图3）
 * 支持邮箱和手机号两种账号类型
 */
import React, { useState, useRef, useEffect } from 'react';
import { Button } from '@pisell/materials';
import { locales } from '@pisell/utils';
import IconFont from '@pisell/materials/src/components/iconfont';
function CodeInput(_ref) {
  var flowData = _ref.flowData,
    _ref$codeLength = _ref.codeLength,
    codeLength = _ref$codeLength === void 0 ? 4 : _ref$codeLength,
    onSubmit = _ref.onSubmit,
    onResend = _ref.onResend,
    onBack = _ref.onBack,
    _ref$countdown = _ref.countdown,
    countdown = _ref$countdown === void 0 ? 0 : _ref$countdown,
    _ref$loading = _ref.loading,
    loading = _ref$loading === void 0 ? false : _ref$loading,
    error = _ref.error,
    onClearError = _ref.onClearError;
  var _useState = useState(Array(codeLength).fill('')),
    _useState2 = _slicedToArray(_useState, 2),
    code = _useState2[0],
    setCode = _useState2[1];
  var inputRefs = useRef([]);
  var canResend = countdown === 0;
  useEffect(function () {
    var _inputRefs$current$;
    // 自动聚焦第一个输入框
    (_inputRefs$current$ = inputRefs.current[0]) === null || _inputRefs$current$ === void 0 || _inputRefs$current$.focus();
  }, []);

  // 当错误出现时，清空输入值
  useEffect(function () {
    if (error) {
      var _inputRefs$current$2;
      setCode(Array(codeLength).fill(''));
      // 聚焦第一个输入框
      (_inputRefs$current$2 = inputRefs.current[0]) === null || _inputRefs$current$2 === void 0 || _inputRefs$current$2.focus();
    }
  }, [error, codeLength]);

  /**
   * 处理单个输入框的值变化
   * @param index 输入框索引
   * @param value 输入的值
   */
  var handleInputChange = function handleInputChange(index, value) {
    // iOS「短信验证码一键填充」/ 粘贴可能会一次性塞进多位数字：
    // - Safari 往往能正常触发
    // - 微信 WebView 更依赖标准的 `autocomplete="one-time-code"`，并且需要允许一次性输入整串数字
    var digitsOnly = value.replace(/\D/g, '');
    if (digitsOnly !== value && value !== '') return; // 只允许数字（允许空字符串用于清空）

    // 一次性输入多位数字时，拆分填充到后续输入框（兼容 iOS one-time-code / IME 粘贴）
    if (digitsOnly.length > 1) {
      var _inputRefs$current$ne;
      if (error && onClearError) onClearError();
      var nextCode = _toConsumableArray(code);
      var maxFillLength = Math.min(codeLength - index, digitsOnly.length);
      for (var offset = 0; offset < maxFillLength; offset += 1) {
        nextCode[index + offset] = digitsOnly[offset];
      }
      setCode(nextCode);
      var nextEmptyIndex = nextCode.findIndex(function (digit) {
        return digit === '';
      });
      if (nextEmptyIndex === -1) {
        onSubmit === null || onSubmit === void 0 || onSubmit(nextCode.join(''));
        return;
      }
      (_inputRefs$current$ne = inputRefs.current[nextEmptyIndex]) === null || _inputRefs$current$ne === void 0 || _inputRefs$current$ne.focus();
      return;
    }

    // 如果用户开始输入且有错误，清除错误
    if (value && error && onClearError) {
      onClearError();
    }
    var newCode = _toConsumableArray(code);
    newCode[index] = value.slice(-1); // 只取最后一个字符
    setCode(newCode);

    // 自动跳到下一个输入框
    if (value && index < codeLength - 1) {
      var _inputRefs$current;
      (_inputRefs$current = inputRefs.current[index + 1]) === null || _inputRefs$current === void 0 || _inputRefs$current.focus();
    }

    // 如果所有输入框都填满了，自动提交
    if (newCode.every(function (digit) {
      return digit !== '';
    })) {
      var fullCode = newCode.join('');
      onSubmit === null || onSubmit === void 0 || onSubmit(fullCode);
    }
  };

  /**
   * 处理键盘按键事件（主要处理退格键）
   * @param index 当前输入框索引
   * @param e 键盘事件
   */
  var handleKeyDown = function handleKeyDown(index, e) {
    // 当前输入框为空且按下退格键时，聚焦到前一个输入框
    if (e.key === 'Backspace' && !code[index] && index > 0) {
      var _inputRefs$current2;
      (_inputRefs$current2 = inputRefs.current[index - 1]) === null || _inputRefs$current2 === void 0 || _inputRefs$current2.focus();
    }
  };

  /**
   * 处理粘贴事件（支持粘贴完整验证码）
   * @param e 剪贴板事件
   */
  var handlePaste = function handlePaste(e) {
    e.preventDefault();
    var pastedData = e.clipboardData.getData('text').trim();
    if (!/^\d+$/.test(pastedData)) return; // 只允许数字

    // 如果用户粘贴且有错误，清除错误
    if (pastedData && error && onClearError) {
      onClearError();
    }
    var newCode = pastedData.slice(0, codeLength).split('');
    while (newCode.length < codeLength) {
      newCode.push('');
    }
    setCode(newCode);

    // 如果粘贴的是完整验证码，自动提交
    if (newCode.every(function (digit) {
      return digit !== '';
    })) {
      onSubmit === null || onSubmit === void 0 || onSubmit(newCode.join(''));
    }
  };

  /**
   * 手动提交验证码
   */
  var handleSubmit = function handleSubmit() {
    var fullCode = code.join('');
    if (fullCode.length === codeLength) {
      onSubmit === null || onSubmit === void 0 || onSubmit(fullCode);
    }
  };

  // 根据账号类型显示不同的标题和描述
  var title = flowData.accountType === 'email' ? locales.getText('pisell-register2-check-email-title') : locales.getText('pisell-register2-check-phone-title');
  var description = flowData.accountType === 'email' ? locales.getText('pisell-register2-check-email-desc') : locales.getText('pisell-register2-check-phone-desc');
  var displayAccount = flowData.account;

  // 根据账号类型显示不同的"没有收到"提示
  var noReceiveText = flowData.accountType === 'email' ? locales.getText('pisell-register2-no-email-received') : locales.getText('pisell-register2-no-message-received');
  return /*#__PURE__*/React.createElement("div", {
    className: "register-step-container code-input-page"
  }, /*#__PURE__*/React.createElement("button", {
    className: "back-button-top",
    onClick: onBack,
    "aria-label": "Go back"
  }, /*#__PURE__*/React.createElement(IconFont, {
    type: "pisell2-arrow-left"
  })), /*#__PURE__*/React.createElement("div", {
    className: "register-step-content"
  }, /*#__PURE__*/React.createElement("h2", {
    className: "register-step-title"
  }, title), /*#__PURE__*/React.createElement("p", {
    className: "register-step-desc"
  }, description, /*#__PURE__*/React.createElement("br", null), displayAccount), /*#__PURE__*/React.createElement("div", {
    className: "code-input-group",
    onPaste: handlePaste
  }, code.map(function (digit, index) {
    return /*#__PURE__*/React.createElement("input", {
      key: index,
      ref: function ref(el) {
        return inputRefs.current[index] = el;
      },
      type: "text",
      inputMode: "numeric"
      // 关键：第一个输入框需要支持 iOS one-time-code 一次性填充整串验证码
      // 否则在微信 WebView 等环境下可能只会塞进第一位或完全不触发
      ,
      autoComplete: index === 0 ? 'one-time-code' : 'off',
      autoCorrect: "off",
      autoCapitalize: "off",
      spellCheck: false,
      maxLength: index === 0 ? codeLength : 1,
      pattern: "[0-9]*",
      className: "code-input-box ".concat(digit ? 'has-value' : '', " ").concat(error ? 'has-error' : ''),
      value: digit,
      onChange: function onChange(e) {
        return handleInputChange(index, e.target.value);
      },
      onKeyDown: function onKeyDown(e) {
        return handleKeyDown(index, e);
      },
      disabled: loading
    });
  })), error && /*#__PURE__*/React.createElement("div", {
    className: "code-input-error"
  }, error), /*#__PURE__*/React.createElement(Button, {
    type: "primary",
    size: "large",
    block: true,
    onClick: handleSubmit,
    loading: loading,
    disabled: code.some(function (digit) {
      return !digit;
    }),
    className: "register-submit-btn"
  }, locales.getText('pisell-common-verify')), /*#__PURE__*/React.createElement(Button, {
    type: "default",
    size: "large",
    block: true,
    onClick: onBack,
    className: "register-back-btn"
  }, locales.getText('pisell-common-back')), /*#__PURE__*/React.createElement("div", {
    className: "register-resend-section"
  }, /*#__PURE__*/React.createElement("span", {
    className: "resend-text"
  }, noReceiveText, " "), /*#__PURE__*/React.createElement("button", {
    className: "resend-link",
    onClick: onResend,
    disabled: !canResend
  }, locales.getText('pisell-common-resend'), countdown > 0 && " (".concat(countdown, " s)")))));
}
export default CodeInput;