function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); }
function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : String(i); }
function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); }
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; }
import { useState, useCallback, useEffect, useRef, useMemo } from 'react';
import { RegisterStep, isValidTransition, getStepDefinition, getFlowConfig, determineVerificationMethod } from "../shared/registerFlow";
export function useRegisterFlow(options) {
  var accountType = options.accountType,
    emailConfig = options.emailConfig,
    phoneConfig = options.phoneConfig,
    _options$initialAccou = options.initialAccount,
    initialAccount = _options$initialAccou === void 0 ? '' : _options$initialAccou,
    onStepChange = options.onStepChange,
    onComplete = options.onComplete;

  // 使用 ref 存储回调，避免它们成为依赖项导致无限渲染
  var onStepChangeRef = useRef(onStepChange);
  var onCompleteRef = useRef(onComplete);

  // 当回调函数变化时更新 ref
  useEffect(function () {
    onStepChangeRef.current = onStepChange;
    onCompleteRef.current = onComplete;
  }, [onStepChange, onComplete]);

  // 确定验证方式 - 使用 useMemo 避免每次渲染都重新计算
  var verificationMethod = useMemo(function () {
    return determineVerificationMethod(accountType, emailConfig, phoneConfig);
  }, [accountType, emailConfig, phoneConfig]);

  // 获取流程配置 - 使用 useMemo 避免每次渲染都重新计算
  var flowConfig = useMemo(function () {
    return getFlowConfig(verificationMethod);
  }, [verificationMethod]);

  // 自动跳转定时器
  var autoTransitionTimer = useRef();

  // 初始化流程数据
  var _useState = useState({
      currentStep: RegisterStep.INITIAL_FORM,
      account: initialAccount,
      accountType: accountType,
      verificationMethod: verificationMethod
    }),
    _useState2 = _slicedToArray(_useState, 2),
    flowData = _useState2[0],
    setFlowData = _useState2[1];

  // 获取当前步骤定义
  var currentStepDef = getStepDefinition(flowData.currentStep);

  // 清除自动跳转定时器
  var clearAutoTransition = useCallback(function () {
    if (autoTransitionTimer.current) {
      clearTimeout(autoTransitionTimer.current);
      autoTransitionTimer.current = undefined;
    }
  }, []);

  // 跳转到指定步骤
  var goToStep = useCallback(function (step, updates) {
    setFlowData(function (prevFlowData) {
      var _updates$verification, _onStepChangeRef$curr, _flowConfig$autoTrans;
      // 如果 updates 中包含新的验证方式，使用新的；否则使用流程数据中的验证方式
      var targetVerificationMethod = (_updates$verification = updates === null || updates === void 0 ? void 0 : updates.verificationMethod) !== null && _updates$verification !== void 0 ? _updates$verification : prevFlowData.verificationMethod;

      // 验证步骤流转是否合法
      if (!isValidTransition(targetVerificationMethod, prevFlowData.currentStep, step)) {
        console.warn("Invalid transition from ".concat(prevFlowData.currentStep, " to ").concat(step, " for ").concat(targetVerificationMethod), '(current verificationMethod:', prevFlowData.verificationMethod, ', target:', targetVerificationMethod, ')');
        return prevFlowData; // 返回原数据，不更新
      }

      // 清除之前的自动跳转定时器
      clearAutoTransition();

      // 更新流程数据
      var newFlowData = _objectSpread(_objectSpread(_objectSpread({}, prevFlowData), updates), {}, {
        currentStep: step
      });

      // 触发步骤变化回调（使用 ref）
      (_onStepChangeRef$curr = onStepChangeRef.current) === null || _onStepChangeRef$curr === void 0 || _onStepChangeRef$curr.call(onStepChangeRef, step, newFlowData);

      // 如果到达完成步骤，触发完成回调（使用 ref）
      if (step === RegisterStep.COMPLETE) {
        var _onCompleteRef$curren;
        (_onCompleteRef$curren = onCompleteRef.current) === null || _onCompleteRef$curren === void 0 || _onCompleteRef$curren.call(onCompleteRef, newFlowData);
      }

      // 检查是否需要自动跳转
      var autoTransition = (_flowConfig$autoTrans = flowConfig.autoTransition) === null || _flowConfig$autoTrans === void 0 ? void 0 : _flowConfig$autoTrans[step];
      if (autoTransition) {
        autoTransitionTimer.current = setTimeout(function () {
          goToStep(autoTransition.nextStep);
        }, autoTransition.delay);
      }
      return newFlowData;
    });
  }, [verificationMethod, flowConfig, clearAutoTransition]);

  // 更新流程数据（不改变步骤）
  var updateFlowData = useCallback(function (updates) {
    setFlowData(function (prev) {
      return _objectSpread(_objectSpread({}, prev), updates);
    });
  }, []);

  // 重置流程
  var resetFlow = useCallback(function () {
    clearAutoTransition();
    setFlowData({
      currentStep: RegisterStep.INITIAL_FORM,
      account: initialAccount,
      accountType: accountType,
      verificationMethod: verificationMethod
    });
  }, [clearAutoTransition, initialAccount, accountType, verificationMethod]);

  // 处理错误
  var handleError = useCallback(function (code, message, targetStep) {
    var errorData = _objectSpread(_objectSpread({}, flowData), {}, {
      error: {
        code: code,
        message: message
      }
    });
    if (targetStep) {
      errorData.currentStep = targetStep;
    }
    setFlowData(errorData);
    onStepChange === null || onStepChange === void 0 || onStepChange(errorData.currentStep, errorData);
  }, [flowData, onStepChange]);

  // 清理定时器
  useEffect(function () {
    return function () {
      clearAutoTransition();
    };
  }, [clearAutoTransition]);
  return {
    flowData: flowData,
    currentStepDef: currentStepDef,
    flowConfig: flowConfig,
    goToStep: goToStep,
    updateFlowData: updateFlowData,
    resetFlow: resetFlow,
    handleError: handleError
  };
}