var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
  for (var name in all)
    __defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
  if (from && typeof from === "object" || typeof from === "function") {
    for (let key of __getOwnPropNames(from))
      if (!__hasOwnProp.call(to, key) && key !== except)
        __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
  }
  return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
  // If the importer is in node compatibility mode or this is not an ESM
  // file that has been converted to a CommonJS file using a Babel-
  // compatible transform (i.e. "__esModule" has not been set), then set
  // "default" to the CommonJS "module.exports" for node compatibility.
  isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
  mod
));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);

// src/pro/Login2.0/Register2.tsx
var Register2_exports = {};
__export(Register2_exports, {
  default: () => Register2_default
});
module.exports = __toCommonJS(Register2_exports);
var import_react = __toESM(require("react"));
var import_antd = require("antd");
var import_materials = require("@pisell/materials");
var import_ahooks = require("ahooks");
var import_classnames = __toESM(require("classnames"));
var import_utils = require("@pisell/utils");
var import_locales = __toESM(require("./locales"));
var import_Header = __toESM(require("./shared/Header"));
var import_PhoneInput = __toESM(require("./components/PhoneInput"));
var import_phoneValidation = require("./components/phoneValidation");
var import_LegalTerms = __toESM(require("./components/LegalTerms"));
var import_index = require("./index.less");
var import_useEngineContext = require("../../hooks/useEngineContext");
var import_useEngineContext2 = __toESM(require("../../hooks/useEngineContext"));
var import_useRegisterFlow = require("./hooks/useRegisterFlow");
var import_useRegistrationMethods = require("./hooks/useRegistrationMethods");
var import_registerFlow = require("./shared/registerFlow");
var import_steps = require("./steps");
var import_steps2 = require("./steps/steps.less");
var import_materials2 = require("@pisell/materials");
var import_usePasswordValidationRules = __toESM(require("./hooks/usePasswordValidationRules"));
var import_OAuthButtonGroup = __toESM(require("./components/OAuthButtonGroup"));
var Register2 = ({
  config,
  visible = true,
  onClose,
  className,
  style,
  onRegister,
  onOAuthLogin,
  onSendVerificationCode,
  onEmailLinkExpired,
  onGoToLogin,
  onError
}) => {
  var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n, _o, _p, _q, _r, _s, _t, _u, _v, _w, _x, _y, _z, _A, _B;
  const [form] = import_antd.Form.useForm();
  const [loading, setLoading] = (0, import_react.useState)(false);
  const [countdown, setCountdown] = (0, import_react.useState)(0);
  const [countries, setCountries] = (0, import_react.useState)([]);
  const [codeError, setCodeError] = (0, import_react.useState)("");
  const pisellOS = (0, import_useEngineContext.usePisellOS)();
  const registerAndLogin = pisellOS == null ? void 0 : pisellOS.getModule("registerAndLogin");
  const context = (0, import_useEngineContext2.default)();
  const utils = ((_a = context == null ? void 0 : context.appHelper) == null ? void 0 : _a.utils) || {};
  const shopId = ((_g = (_f = (_e = (_d = (_c = (_b = utils.getStore) == null ? void 0 : _b.call(utils)) == null ? void 0 : _c.getState) == null ? void 0 : _d.call(_c)) == null ? void 0 : _e.global) == null ? void 0 : _f.shop) == null ? void 0 : _g.id) || 9;
  const [emailLinkVerifyStatus, setEmailLinkVerifyStatus] = (0, import_react.useState)(null);
  const [verifiedEmail, setVerifiedEmail] = (0, import_react.useState)("");
  const normalizedRegistrationMethods = (0, import_react.useMemo)(() => {
    var _a2, _b2, _c2, _d2, _e2, _f2, _g2, _h2, _i2, _j2, _k2, _l2, _m2, _n2;
    if (config.registrationMethods && config.registrationMethods.length > 0) {
      return config.registrationMethods;
    }
    const methods = [];
    if ((_a2 = config.email) == null ? void 0 : _a2.enable_email) {
      methods.push({
        type: "email",
        verificationMethod: config.email.registration_verification ? config.email.registration_verification : "verification_code"
      });
    }
    if ((_b2 = config.phone) == null ? void 0 : _b2.enable_phone_number) {
      methods.push({
        type: "phone",
        verificationMethod: "verification_code"
        // 手机号仅支持验证码
      });
    }
    if (((_d2 = (_c2 = config.oauth) == null ? void 0 : _c2.google) == null ? void 0 : _d2.enabled) && ((_f2 = (_e2 = config.oauth) == null ? void 0 : _e2.google) == null ? void 0 : _f2.client_id)) {
      methods.push({
        type: "google",
        clientId: config.oauth.google.client_id
      });
    }
    if (((_h2 = (_g2 = config.oauth) == null ? void 0 : _g2.facebook) == null ? void 0 : _h2.enabled) && ((_j2 = (_i2 = config.oauth) == null ? void 0 : _i2.facebook) == null ? void 0 : _j2.app_id)) {
      methods.push({
        type: "facebook",
        appId: config.oauth.facebook.app_id
      });
    }
    if (((_l2 = (_k2 = config.oauth) == null ? void 0 : _k2.apple) == null ? void 0 : _l2.enabled) && ((_n2 = (_m2 = config.oauth) == null ? void 0 : _m2.apple) == null ? void 0 : _n2.client_id)) {
      methods.push({
        type: "apple",
        clientId: config.oauth.apple.client_id
      });
    }
    return methods;
  }, [config.registrationMethods, config.email, config.phone, config.oauth]);
  const getDefaultAuthMethod = () => {
    var _a2, _b2, _c2, _d2;
    if (normalizedRegistrationMethods.length > 0) {
      if (config.defaultAuthMethod) {
        const method = normalizedRegistrationMethods.find(
          (m) => m.type === config.defaultAuthMethod
        );
        if (method) {
          return config.defaultAuthMethod;
        }
      }
      return normalizedRegistrationMethods[0].type;
    }
    if (config.defaultAuthMethod) {
      return config.defaultAuthMethod;
    }
    if (((_a2 = config.phone) == null ? void 0 : _a2.enable_phone_number) && !((_b2 = config.email) == null ? void 0 : _b2.enable_email)) {
      return "phone";
    }
    if (((_c2 = config.email) == null ? void 0 : _c2.enable_email) && !((_d2 = config.phone) == null ? void 0 : _d2.enable_phone_number)) {
      return "email";
    }
    return "email";
  };
  const [currentAuthMethod, setCurrentAuthMethod] = (0, import_react.useState)(
    () => getDefaultAuthMethod()
  );
  const getRegistrationMethodConfig = (0, import_react.useCallback)(
    (type) => {
      return normalizedRegistrationMethods.find(
        (method) => method.type === type
      );
    },
    [normalizedRegistrationMethods]
  );
  const getCurrentVerificationMethod = (0, import_react.useCallback)(() => {
    var _a2;
    const methodConfig = getRegistrationMethodConfig(currentAuthMethod);
    if (methodConfig && "verificationMethod" in methodConfig) {
      return methodConfig.verificationMethod;
    }
    if (currentAuthMethod === "email") {
      return ((_a2 = config.email) == null ? void 0 : _a2.registration_verification) || "verification_code";
    } else if (currentAuthMethod === "phone") {
      return "verification_code";
    }
    return "verification_code";
  }, [
    currentAuthMethod,
    getRegistrationMethodConfig,
    config.email,
    config.phone
  ]);
  const passwordValidationRules = (0, import_usePasswordValidationRules.default)(
    (_h = config.ui) == null ? void 0 : _h.passwordRules,
    {
      translate: import_utils.locales.getText,
      fallbackMinLength: 6,
      messageKeys: {
        required: "pisell-register2-password-required",
        minLength: "pisell-register2-password-min-length",
        requireUppercase: "pisell-set-password-require-uppercase",
        requireLowercase: "pisell-set-password-require-lowercase",
        requireNumber: "pisell-set-password-require-number",
        requireSpecialCharacters: "pisell-set-password-require-special",
        summary: "pisell-set-password-must-contain"
      }
    }
  );
  const isRegistrationMethodEnabled = (0, import_react.useCallback)(
    (type) => {
      return normalizedRegistrationMethods.some(
        (method) => method.type === type
      );
    },
    [normalizedRegistrationMethods]
  );
  const { shouldShowDivider, hasEmailAndPhone } = (0, import_useRegistrationMethods.useRegistrationMethods)(isRegistrationMethodEnabled);
  const handleStepChange = (0, import_react.useCallback)(() => {
  }, []);
  const handleComplete = (0, import_react.useCallback)(
    (data) => {
      var _a2;
      const apiResponse = (_a2 = data.extraData) == null ? void 0 : _a2.apiResponse;
      onRegister == null ? void 0 : onRegister(
        apiResponse || (data == null ? void 0 : data.data),
        data.accountType,
        {
          account: data.account,
          password: data.password || ""
        },
        config.channel
      );
    },
    [onRegister, config.channel]
  );
  const {
    flowData,
    currentStepDef,
    goToStep,
    updateFlowData,
    resetFlow,
    handleError
  } = (0, import_useRegisterFlow.useRegisterFlow)({
    accountType: currentAuthMethod,
    emailConfig: config.email,
    phoneConfig: config.phone,
    initialAccount: "",
    onStepChange: handleStepChange,
    onComplete: handleComplete
  });
  (0, import_react.useEffect)(() => {
    const fetchCountries = async () => {
      try {
        if (registerAndLogin == null ? void 0 : registerAndLogin.getCountries) {
          const countriesList = await registerAndLogin.getCountries();
          setCountries(countriesList || []);
        }
      } catch (error) {
        console.error("Failed to fetch countries:", error);
      }
    };
    fetchCountries();
  }, [registerAndLogin]);
  (0, import_react.useEffect)(() => {
    const verifyEmailLink = async () => {
      var _a2, _b2;
      if (!((_a2 = config.emailLinkVerification) == null ? void 0 : _a2.enabled) || !((_b2 = config.emailLinkVerification) == null ? void 0 : _b2.code)) {
        return;
      }
      setEmailLinkVerifyStatus("verifying");
      try {
        const result = await registerAndLogin.checkEmailLinkCode({
          code: config.emailLinkVerification.code
        });
        if (result.code === 200 && result.data.valid) {
          updateFlowData({
            emailLinkCode: config.emailLinkVerification.code,
            account: result.data.email || "",
            accountType: "email",
            verificationMethod: import_registerFlow.VerificationMethod.EMAIL_LINK
          });
          setVerifiedEmail(result.data.email);
          setEmailLinkVerifyStatus("success");
          goToStep(import_registerFlow.RegisterStep.SET_PASSWORD);
        } else if (result.code === 50011) {
          setEmailLinkVerifyStatus("expired");
        } else if (!result.data.valid) {
          setEmailLinkVerifyStatus("already_used");
        } else {
          setEmailLinkVerifyStatus(null);
          import_antd.message.error(result.message || "验证失败，请稍后重试");
        }
      } catch (error) {
        console.error("Email link verification failed:", error);
        import_antd.message.error("验证失败，请稍后重试");
        setEmailLinkVerifyStatus(null);
      }
    };
    verifyEmailLink();
  }, [config.emailLinkVerification, registerAndLogin]);
  (0, import_react.useEffect)(() => {
    if (!visible) {
      form.setFieldsValue({ password: "" });
      form.setFieldsValue({ confirmPassword: "" });
    }
  }, [visible, form]);
  (0, import_react.useEffect)(() => {
    const newAuthMethod = getDefaultAuthMethod();
    if (newAuthMethod !== currentAuthMethod) {
      setCurrentAuthMethod(newAuthMethod);
      form.resetFields(["account"]);
    }
  }, [normalizedRegistrationMethods, config.defaultAuthMethod]);
  (0, import_react.useEffect)(() => {
    var _a2, _b2, _c2, _d2, _e2, _f2, _g2;
    import_utils.locales.init(
      import_locales.default,
      ((_e2 = (_d2 = (_c2 = (_b2 = (_a2 = context.appHelper.utils) == null ? void 0 : _a2.getApp) == null ? void 0 : _b2.call(_a2)) == null ? void 0 : _c2.locales) == null ? void 0 : _d2.getLocale) == null ? void 0 : _e2.call(_d2)) || ((_g2 = (_f2 = context.appHelper.utils) == null ? void 0 : _f2.storage) == null ? void 0 : _g2.get("umi_locale")) || "en"
    );
  }, []);
  (0, import_react.useEffect)(() => {
    if (countdown > 0) {
      const timer = setTimeout(() => {
        setCountdown(countdown - 1);
      }, 1e3);
      return () => clearTimeout(timer);
    }
  }, [countdown]);
  const handleSendCode = async () => {
    try {
      const values = await form.validateFields(["account"]);
      const account = values.account;
      setLoading(true);
      const type = currentAuthMethod === "email" ? "email" : "phone";
      let res;
      if (currentAuthMethod === "email") {
        const emailVerificationMethod = getCurrentVerificationMethod();
        if (emailVerificationMethod === "verification_link") {
          res = await registerAndLogin.sendEmailRegisterLink(account);
        } else {
          res = await registerAndLogin.sendEmailVerificationCode({
            type: "email",
            target: account,
            purpose: "register"
          });
        }
      } else {
        res = await registerAndLogin.sendSmsRegisterCode(account);
      }
      const accountForCallback = currentAuthMethod === "phone" && typeof account === "object" ? `+${account.country_calling_code}${account.phone}` : account;
      await (onSendVerificationCode == null ? void 0 : onSendVerificationCode(accountForCallback, type, config.channel));
      if (res.code === 200) {
        updateFlowData({ account, accountType: currentAuthMethod });
        const verificationMethod = getCurrentVerificationMethod();
        if (verificationMethod === "verification_link") {
          goToStep(import_registerFlow.RegisterStep.WAIT_EMAIL_LINK, {
            account,
            accountType: currentAuthMethod,
            verificationMethod: import_registerFlow.VerificationMethod.EMAIL_LINK
            // 同时更新验证方式
          });
          setCountdown(60);
        } else if (verificationMethod === "verification_code") {
          goToStep(import_registerFlow.RegisterStep.INPUT_VERIFICATION_CODE, {
            account,
            accountType: currentAuthMethod
          });
          setCountdown(60);
          import_antd.message.success(import_utils.locales.getText("pisell-login2-code-sent"));
        }
      } else if (res.code === 5002) {
        goToStep(import_registerFlow.RegisterStep.EMAIL_ALREADY_REGISTERED, {
          account,
          accountType: currentAuthMethod
        });
      } else {
        import_antd.message.error(res.message);
      }
    } catch (error) {
      if (error.errorFields) {
        return;
      }
      handleError(
        "SEND_CODE_FAILED",
        error.message || "Failed to send verification code"
      );
      import_antd.message.error(error == null ? void 0 : error.message);
    } finally {
      setLoading(false);
    }
  };
  const handleRegister = async () => {
    try {
      setLoading(true);
      const values = await form.validateFields();
      const registerData = {
        account: values.account,
        password: values.password
      };
      await (onRegister == null ? void 0 : onRegister(registerData, currentAuthMethod, config.channel));
      import_antd.message.success(import_utils.locales.getText("pisell-register2-register-success"));
    } catch (error) {
      if (error.errorFields) {
        return;
      }
      import_antd.message.error((error == null ? void 0 : error.message) || "Registration failed");
    } finally {
      setLoading(false);
    }
  };
  const handleFormSubmit = (e) => {
    e == null ? void 0 : e.preventDefault();
    if (isEmailNoVerification) {
      handleRegister();
    } else if (needsVerification) {
      handleSendCode();
    } else {
      handleRegister();
    }
  };
  const handleOAuthClickInternal = async (provider) => {
    var _a2, _b2, _c2;
    try {
      setLoading(true);
      if (provider === "facebook") {
        const fbConfig = (_a2 = config == null ? void 0 : config.registrationMethods) == null ? void 0 : _a2.find((n) => n.type === "facebook");
        const token = fbConfig == null ? void 0 : fbConfig.appId;
        if (!token) {
          throw new Error("Facebook app_id not configured");
        }
        const res = await registerAndLogin.loginWithFacebook(token);
        if (res.data) {
          await (onRegister == null ? void 0 : onRegister(
            res.data,
            "facebook",
            { account: "", password: "" },
            config.channel
          ));
        }
      } else if (provider === "apple") {
        const appleConfig = (_b2 = config == null ? void 0 : config.registrationMethods) == null ? void 0 : _b2.find((n) => n.type === "apple");
        const token = appleConfig == null ? void 0 : appleConfig.clientId;
        if (token) {
          const res = await registerAndLogin.loginWithApple(token);
          if (res.data) {
            await (onRegister == null ? void 0 : onRegister(
              res.data,
              "apple",
              { account: "", password: "" },
              config.channel
            ));
          }
        } else {
          throw new Error("Apple client_id not configured");
        }
      } else if (provider === "google") {
        const googleConfig = (_c2 = config == null ? void 0 : config.registrationMethods) == null ? void 0 : _c2.find((n) => n.type === "google");
        const token = googleConfig == null ? void 0 : googleConfig.clientId;
        if (token) {
          const res = await registerAndLogin.loginWithGoogle(token);
          if (res.data) {
            await (onRegister == null ? void 0 : onRegister(
              res.data,
              "google",
              { account: "", password: "" },
              config.channel
            ));
          }
        } else {
          throw new Error("Google client_id not configured");
        }
      }
      await (onOAuthLogin == null ? void 0 : onOAuthLogin(provider, config.channel));
    } catch (error) {
      if (error.message === "facebook_login_cancel") {
        return import_antd.message.error(import_utils.locales.getText("pisell-register2-facebook-login-canceled"));
      }
      console.error(`${provider} login error:`, error);
      import_antd.message.error((error == null ? void 0 : error.message) || `${provider} login failed`);
      onError == null ? void 0 : onError(error, provider);
    } finally {
      setLoading(false);
    }
  };
  const { run: handleOAuthClick } = (0, import_ahooks.useDebounceFn)(handleOAuthClickInternal, {
    wait: 200,
    leading: true,
    trailing: false
  });
  const oauthProviders = (0, import_react.useMemo)(() => {
    const providers = [];
    if (isRegistrationMethodEnabled("google")) {
      providers.push({
        key: "google",
        label: import_utils.locales.getText("pisell-register2-continue-with-google"),
        icon: /* @__PURE__ */ import_react.default.createElement("span", { className: "oauth-icon" }, "G"),
        onClick: () => handleOAuthClick("google"),
        className: "oauth-button google"
      });
    }
    if (isRegistrationMethodEnabled("facebook")) {
      providers.push({
        key: "facebook",
        label: import_utils.locales.getText("pisell-register2-continue-with-facebook"),
        icon: /* @__PURE__ */ import_react.default.createElement(import_materials2.Iconfont, { type: "pisell2-facebook", className: "oauth-icon" }),
        onClick: () => handleOAuthClick("facebook"),
        className: "oauth-button facebook"
      });
    }
    if (isRegistrationMethodEnabled("apple")) {
      providers.push({
        key: "apple",
        label: import_utils.locales.getText("pisell-register2-continue-with-apple"),
        icon: /* @__PURE__ */ import_react.default.createElement(import_materials2.Iconfont, { type: "pisell2-apple", className: "oauth-icon" }),
        onClick: () => handleOAuthClick("apple"),
        className: "oauth-button apple"
      });
    }
    return providers;
  }, [handleOAuthClick, isRegistrationMethodEnabled]);
  const handleResendCode = async () => {
    if (countdown > 0) return;
    try {
      setLoading(true);
      const type = currentAuthMethod === "email" ? "email" : "phone";
      const verificationMethod = getCurrentVerificationMethod();
      let res;
      if (currentAuthMethod === "email") {
        if (verificationMethod === "verification_link") {
          res = await registerAndLogin.resendEmailRegisterLink();
        } else {
          res = await registerAndLogin.sendEmailVerificationCode({
            type: "email",
            target: flowData.account,
            purpose: "register"
          });
        }
      } else {
        res = await registerAndLogin.sendSmsRegisterCode(flowData.account);
      }
      if (res.code === 200) {
        setCountdown(60);
        let successMessage = "";
        if (currentAuthMethod === "email") {
          if (verificationMethod === "verification_link") {
            successMessage = import_utils.locales.getText("pisell-register2-email-link-resent");
          } else {
            successMessage = import_utils.locales.getText("pisell-register2-email-code-resent");
          }
        } else {
          successMessage = import_utils.locales.getText("pisell-register2-phone-code-resent");
        }
        import_antd.message.success(successMessage);
      } else {
        let errorMessage = "";
        if (currentAuthMethod === "email") {
          if (verificationMethod === "verification_link") {
            errorMessage = import_utils.locales.getText("pisell-register2-email-link-resend-failed");
          } else {
            errorMessage = import_utils.locales.getText("pisell-register2-email-code-resend-failed");
          }
        } else {
          errorMessage = import_utils.locales.getText("pisell-register2-phone-code-resend-failed");
        }
        import_antd.message.error(res.message || errorMessage);
      }
    } catch (error) {
      let errorMessage = "";
      const verificationMethod = getCurrentVerificationMethod();
      if (currentAuthMethod === "email") {
        if (verificationMethod === "verification_link") {
          errorMessage = import_utils.locales.getText("pisell-register2-email-link-resend-failed");
        } else {
          errorMessage = import_utils.locales.getText("pisell-register2-email-code-resend-failed");
        }
      } else {
        errorMessage = import_utils.locales.getText("pisell-register2-phone-code-resend-failed");
      }
      import_antd.message.error(errorMessage);
    } finally {
      setLoading(false);
    }
  };
  const handleVerifyCode = async (code) => {
    try {
      setLoading(true);
      setCodeError("");
      const type = currentAuthMethod === "email" ? "email" : "phone";
      let res;
      if (type === "email") {
        res = await registerAndLogin.checkEmailCode({
          email: flowData.account,
          shop_id: shopId,
          code,
          action: "customer_registration_code"
        });
      } else {
        const phoneData = flowData.account;
        res = await registerAndLogin.checkMobileCode({
          phone: phoneData.phone,
          country_calling_code: phoneData.country_calling_code,
          code,
          action: "register"
        });
      }
      if (res.code === 200 && res.data.valid) {
        updateFlowData({ verificationCode: code });
        goToStep(import_registerFlow.RegisterStep.VERIFICATION_SUCCESS);
      } else {
        const errorMessage = (res == null ? void 0 : res.message) || import_utils.locales.getText("pisell-register2-invalid-verification-code");
        setCodeError(errorMessage);
      }
    } catch (error) {
      console.error(error);
      setCodeError((error == null ? void 0 : error.message) || import_utils.locales.getText("pisell-register2-verification-failed"));
    } finally {
      setLoading(false);
    }
  };
  const handleSetPassword = async (password, confirmPassword) => {
    try {
      setLoading(true);
      let res;
      if (flowData.emailLinkCode) {
        res = await registerAndLogin.verifyEmailRegistrationLink({
          code: flowData.emailLinkCode,
          password
        });
      } else if (currentAuthMethod === "email") {
        res = await registerAndLogin.emailCodeRegister({
          email: flowData.account,
          code: flowData.verificationCode,
          password
        });
      } else {
        const phoneData = flowData.account;
        res = await registerAndLogin.phoneCodeRegister({
          phone: phoneData.phone,
          code: flowData.verificationCode,
          password,
          country_calling_code: phoneData.country_calling_code
        });
      }
      if (res.code === 200) {
        updateFlowData({
          password,
          extraData: {
            ...flowData.extraData,
            apiResponse: res.data
          }
        });
        goToStep(import_registerFlow.RegisterStep.COMPLETE);
        import_antd.message.success(import_utils.locales.getText("pisell-register2-register-success"));
      } else {
        const error = new Error(res.message || "Registration failed");
        onError == null ? void 0 : onError(error, currentAuthMethod);
        import_antd.message.error(res.message || import_utils.locales.getText("pisell-register2-registration-failed"));
      }
    } catch (error) {
      import_antd.message.error(error.message, import_utils.locales.getText("pisell-register2-failed-to-complete"));
      console.error(error);
    } finally {
      setLoading(false);
    }
  };
  const handleBackToInitialForm = (0, import_react.useCallback)(() => {
    setCodeError("");
    goToStep(import_registerFlow.RegisterStep.INITIAL_FORM, {
      verificationMethod: flowData.verificationMethod
    });
  }, [goToStep, flowData]);
  const handleEditAccount = () => {
    if (flowData.account) {
      form.setFieldsValue({ account: flowData.account });
    }
    handleBackToInitialForm();
  };
  const handleGoToLogin = () => {
    if (onGoToLogin) {
      onGoToLogin();
    }
  };
  const handleSwitchAuthMethod = (method) => {
    setCurrentAuthMethod(method);
    form.resetFields(["account"]);
    resetFlow();
  };
  const handleBackToRegistration = () => {
    setEmailLinkVerifyStatus(null);
    setVerifiedEmail("");
    form.resetFields();
    resetFlow();
    onEmailLinkExpired == null ? void 0 : onEmailLinkExpired();
  };
  const renderAccountInput = () => {
    var _a2, _b2, _c2, _d2, _e2, _f2, _g2, _h2;
    const placeholder = currentAuthMethod === "email" ? import_utils.locales.getText("pisell-login2-email-placeholder") : "Enter your phone number";
    if (currentAuthMethod === "phone") {
      const phoneLabel = ((_b2 = (_a2 = ui == null ? void 0 : ui.formLabels) == null ? void 0 : _a2.phone) == null ? void 0 : _b2.show) !== false ? ((_d2 = (_c2 = ui == null ? void 0 : ui.formLabels) == null ? void 0 : _c2.phone) == null ? void 0 : _d2.text) || import_utils.locales.getText("pisell-login2-phone-label") : void 0;
      const phoneRules = (0, import_phoneValidation.createPhoneValidationRules)(import_utils.locales.getText, true);
      return /* @__PURE__ */ import_react.default.createElement(import_antd.Form.Item, { name: "account", label: phoneLabel, rules: phoneRules, validateTrigger: ["onBlur", "onSubmit"] }, /* @__PURE__ */ import_react.default.createElement(
        import_PhoneInput.default,
        {
          placeholder,
          size: "large",
          countries: (countries == null ? void 0 : countries.length) > 0 ? countries : [],
          valueFormat: "object"
        }
      ));
    }
    const emailRules = [
      {
        required: true,
        message: import_utils.locales.getText("pisell-register2-email-required")
      },
      {
        type: "email",
        message: import_utils.locales.getText("pisell-register2-email-invalid")
      }
    ];
    const emailLabel = ((_f2 = (_e2 = ui == null ? void 0 : ui.formLabels) == null ? void 0 : _e2.email) == null ? void 0 : _f2.show) !== false ? ((_h2 = (_g2 = ui == null ? void 0 : ui.formLabels) == null ? void 0 : _g2.email) == null ? void 0 : _h2.text) || import_utils.locales.getText("pisell-login2-email-label") : void 0;
    return /* @__PURE__ */ import_react.default.createElement(import_antd.Form.Item, { name: "account", label: emailLabel, rules: emailRules, validateTrigger: ["onBlur", "onSubmit"] }, /* @__PURE__ */ import_react.default.createElement(
      import_materials.Input,
      {
        size: "large",
        placeholder,
        className: "login2-input"
      }
    ));
  };
  const renderStepPage = () => {
    var _a2;
    switch (flowData.currentStep) {
      case import_registerFlow.RegisterStep.WAIT_EMAIL_LINK:
        return /* @__PURE__ */ import_react.default.createElement(
          import_steps.WaitEmailLink,
          {
            flowData,
            onResend: handleResendCode,
            onBack: handleBackToInitialForm,
            onEditEmail: handleEditAccount,
            countdown,
            verificationMethod: flowData.verificationMethod
          }
        );
      case import_registerFlow.RegisterStep.EMAIL_ALREADY_REGISTERED:
        return /* @__PURE__ */ import_react.default.createElement(
          import_steps.EmailAlreadyRegistered,
          {
            flowData,
            onGoToLogin: handleGoToLogin,
            onBack: handleBackToInitialForm
          }
        );
      case import_registerFlow.RegisterStep.INPUT_VERIFICATION_CODE:
        return /* @__PURE__ */ import_react.default.createElement(
          import_steps.CodeInput,
          {
            flowData,
            codeLength: 4,
            onSubmit: handleVerifyCode,
            onResend: handleResendCode,
            onBack: handleBackToInitialForm,
            countdown,
            loading,
            error: codeError,
            onClearError: () => setCodeError("")
          }
        );
      case import_registerFlow.RegisterStep.VERIFICATION_SUCCESS:
        return /* @__PURE__ */ import_react.default.createElement(import_steps.VerificationSuccess, { flowData });
      case import_registerFlow.RegisterStep.SET_PASSWORD:
        return /* @__PURE__ */ import_react.default.createElement(
          import_steps.SetPassword,
          {
            flowData,
            onSubmit: handleSetPassword,
            onBack: () => goToStep(import_registerFlow.RegisterStep.INPUT_VERIFICATION_CODE),
            loading,
            passwordRules: (_a2 = config.ui) == null ? void 0 : _a2.passwordRules,
            scenario: "create"
          }
        );
      case import_registerFlow.RegisterStep.COMPLETE:
        return /* @__PURE__ */ import_react.default.createElement("div", { className: "register-step-container" }, /* @__PURE__ */ import_react.default.createElement("div", { className: "register-step-content" }, /* @__PURE__ */ import_react.default.createElement("div", { className: "success-icon-wrapper" }, /* @__PURE__ */ import_react.default.createElement("svg", { width: "64", height: "64", viewBox: "0 0 64 64", fill: "none" }, /* @__PURE__ */ import_react.default.createElement(
          "circle",
          {
            cx: "32",
            cy: "32",
            r: "32",
            fill: "#10B981",
            fillOpacity: "0.1"
          }
        ), /* @__PURE__ */ import_react.default.createElement(
          "path",
          {
            d: "M22 32L28 38L42 24",
            stroke: "#10B981",
            strokeWidth: "3",
            strokeLinecap: "round",
            strokeLinejoin: "round"
          }
        ))), /* @__PURE__ */ import_react.default.createElement("h2", { className: "register-step-title" }, import_utils.locales.getText("pisell-register2-complete-title")), /* @__PURE__ */ import_react.default.createElement("p", { className: "register-step-desc" }, import_utils.locales.getText("pisell-register2-redirecting"))));
      default:
        return null;
    }
  };
  const handleSetPasswordSubmit = async (password, confirmPassword) => {
    try {
      setLoading(true);
      const res = await registerAndLogin.verifyEmailRegistrationLink({
        code: config.emailLinkVerification.code,
        password
      });
      if (res.code === 200) {
        import_antd.message.success(import_utils.locales.getText("pisell-register2-register-success"));
        await (onRegister == null ? void 0 : onRegister(
          res.data,
          "email",
          { account: verifiedEmail, password },
          config.channel
        ));
      } else {
        import_antd.message.error(
          res.message || import_utils.locales.getText("pisell-register2-registration-failed")
        );
      }
    } catch (error) {
      import_antd.message.error(
        (error == null ? void 0 : error.message) || import_utils.locales.getText("pisell-register2-failed-to-complete")
      );
    } finally {
      setLoading(false);
    }
  };
  if (!visible) {
    return null;
  }
  const { ui } = config;
  if ((_i = config.emailLinkVerification) == null ? void 0 : _i.enabled) {
    if (emailLinkVerifyStatus === "verifying") {
      return /* @__PURE__ */ import_react.default.createElement(
        "div",
        {
          className: (0, import_classnames.default)(
            "login2-container",
            "register-flow-container",
            className
          ),
          style: {
            ...style,
            "--theme-color": (ui == null ? void 0 : ui.themeColor) || "#7F56D9"
          }
        },
        /* @__PURE__ */ import_react.default.createElement(import_steps.VerifyingEmailLink, null)
      );
    }
    if (emailLinkVerifyStatus === "expired") {
      return /* @__PURE__ */ import_react.default.createElement(
        "div",
        {
          className: (0, import_classnames.default)(
            "login2-container",
            "register-flow-container",
            className
          ),
          style: {
            ...style,
            "--theme-color": (ui == null ? void 0 : ui.themeColor) || "#7F56D9"
          }
        },
        /* @__PURE__ */ import_react.default.createElement(
          import_steps.EmailLinkExpired,
          {
            onBackToRegistration: handleBackToRegistration,
            onGoToLogin
          }
        )
      );
    }
    if (emailLinkVerifyStatus === "already_used") {
      return /* @__PURE__ */ import_react.default.createElement(
        "div",
        {
          className: (0, import_classnames.default)(
            "login2-container",
            "register-flow-container",
            className
          ),
          style: {
            ...style,
            "--theme-color": (ui == null ? void 0 : ui.themeColor) || "#7F56D9"
          }
        },
        /* @__PURE__ */ import_react.default.createElement(import_steps.EmailLinkAlreadyUsed, { onGoToLogin })
      );
    }
    if (emailLinkVerifyStatus === "success") {
      return /* @__PURE__ */ import_react.default.createElement(
        "div",
        {
          className: (0, import_classnames.default)(
            "login2-container",
            "register-flow-container",
            className
          ),
          style: {
            ...style,
            "--theme-color": (ui == null ? void 0 : ui.themeColor) || "#7F56D9"
          }
        },
        /* @__PURE__ */ import_react.default.createElement(
          import_steps.SetPassword,
          {
            flowData: { ...flowData, account: verifiedEmail },
            onSubmit: handleSetPasswordSubmit,
            loading,
            passwordRules: (_j = config.ui) == null ? void 0 : _j.passwordRules,
            scenario: "create"
          }
        )
      );
    }
  }
  const isEmailVerificationLink = currentAuthMethod === "email" && getCurrentVerificationMethod() === "verification_link";
  const isEmailVerificationCode = currentAuthMethod === "email" && getCurrentVerificationMethod() === "verification_code";
  const isEmailNoVerification = currentAuthMethod === "email" && getCurrentVerificationMethod() === "none";
  const isPhoneVerificationCode = currentAuthMethod === "phone" && getCurrentVerificationMethod() === "verification_code";
  const needsVerification = isEmailVerificationLink || isEmailVerificationCode || isPhoneVerificationCode;
  if (flowData.currentStep !== import_registerFlow.RegisterStep.INITIAL_FORM) {
    const showHeader = flowData.currentStep !== import_registerFlow.RegisterStep.INPUT_VERIFICATION_CODE && flowData.currentStep !== import_registerFlow.RegisterStep.WAIT_EMAIL_LINK && flowData.currentStep !== import_registerFlow.RegisterStep.SET_PASSWORD && flowData.currentStep !== import_registerFlow.RegisterStep.EMAIL_ALREADY_REGISTERED;
    return /* @__PURE__ */ import_react.default.createElement(
      "div",
      {
        className: (0, import_classnames.default)(
          "login2-container",
          "register-flow-container",
          className
        ),
        style: {
          ...style,
          "--theme-color": (ui == null ? void 0 : ui.themeColor) || "#7F56D9"
        }
      },
      showHeader && /* @__PURE__ */ import_react.default.createElement(import_Header.default, { ui }),
      renderStepPage()
    );
  }
  return /* @__PURE__ */ import_react.default.createElement(
    "div",
    {
      className: (0, import_classnames.default)("login2-container", "register2-container", className),
      style: {
        ...style,
        "--theme-color": (ui == null ? void 0 : ui.themeColor) || "#7F56D9"
      }
    },
    /* @__PURE__ */ import_react.default.createElement(import_Header.default, { ui }),
    /* @__PURE__ */ import_react.default.createElement("div", { className: "login2-content" }, (isRegistrationMethodEnabled("email") || isRegistrationMethodEnabled("phone")) && /* @__PURE__ */ import_react.default.createElement(
      import_antd.Form,
      {
        form,
        layout: "vertical",
        className: "login2-form",
        size: "large"
      },
      /* @__PURE__ */ import_react.default.createElement(
        import_antd.Form.Item,
        {
          label: currentAuthMethod === "email" ? ((_m = (_l = (_k = config.ui) == null ? void 0 : _k.formLabels) == null ? void 0 : _l.email) == null ? void 0 : _m.show) !== false ? ((_p = (_o = (_n = config.ui) == null ? void 0 : _n.formLabels) == null ? void 0 : _o.email) == null ? void 0 : _p.text) || import_utils.locales.getText("pisell-login2-email-label") : void 0 : ((_s = (_r = (_q = config.ui) == null ? void 0 : _q.formLabels) == null ? void 0 : _r.phone) == null ? void 0 : _s.show) !== false ? ((_v = (_u = (_t = config.ui) == null ? void 0 : _t.formLabels) == null ? void 0 : _u.phone) == null ? void 0 : _v.text) || import_utils.locales.getText("pisell-login2-phone-label") : void 0,
          name: "account",
          rules: currentAuthMethod === "email" ? [
            {
              required: true,
              message: import_utils.locales.getText("pisell-register2-email-required")
            },
            {
              type: "email",
              message: import_utils.locales.getText("pisell-register2-email-invalid")
            }
          ] : (0, import_phoneValidation.createPhoneValidationRules)(import_utils.locales.getText, true),
          validateTrigger: ["onBlur", "onSubmit"],
          className: currentAuthMethod === "phone" ? "phone-input-form-item" : ""
        },
        currentAuthMethod === "phone" ? /* @__PURE__ */ import_react.default.createElement(
          import_PhoneInput.default,
          {
            size: "large",
            placeholder: import_utils.locales.getText("pisell-register2-phone-placeholder"),
            className: "login2-phone-input",
            countries,
            valueFormat: "object",
            onKeyDown: (e) => {
              if (e.key === "Enter" && !e.shiftKey && !e.ctrlKey && !e.metaKey) {
                e.preventDefault();
                handleFormSubmit(e);
              }
            }
          }
        ) : /* @__PURE__ */ import_react.default.createElement(
          import_materials.Input,
          {
            size: "large",
            placeholder: import_utils.locales.getText("pisell-register2-email-placeholder"),
            className: "login2-email-input",
            autoComplete: "email",
            onKeyDown: (e) => {
              if (e.key === "Enter" && !e.shiftKey && !e.ctrlKey && !e.metaKey) {
                e.preventDefault();
                handleFormSubmit(e);
              }
            }
          }
        )
      ),
      (!needsVerification || isEmailNoVerification) && /* @__PURE__ */ import_react.default.createElement(
        import_antd.Form.Item,
        {
          label: ((_y = (_x = (_w = config.ui) == null ? void 0 : _w.formLabels) == null ? void 0 : _x.password) == null ? void 0 : _y.show) !== false ? ((_B = (_A = (_z = config.ui) == null ? void 0 : _z.formLabels) == null ? void 0 : _A.password) == null ? void 0 : _B.text) || import_utils.locales.getText("pisell-register2-password-label") : void 0,
          name: "password",
          rules: passwordValidationRules,
          validateTrigger: ["onBlur", "onSubmit"]
        },
        /* @__PURE__ */ import_react.default.createElement(
          import_materials.Input.Password,
          {
            size: "large",
            placeholder: import_utils.locales.getText("pisell-register2-password-placeholder"),
            className: "login2-password-input",
            autoComplete: "new-password",
            onKeyDown: (e) => {
              if (e.key === "Enter" && !e.shiftKey && !e.ctrlKey && !e.metaKey) {
                e.preventDefault();
                handleFormSubmit(e);
              }
            }
          }
        )
      ),
      /* @__PURE__ */ import_react.default.createElement(
        import_materials.Button,
        {
          type: "primary",
          size: "large",
          block: true,
          htmlType: "button",
          loading,
          onClick: handleFormSubmit,
          className: "login2-submit-button"
        },
        isEmailNoVerification ? import_utils.locales.getText("pisell-common-continue") : needsVerification ? import_utils.locales.getText("pisell-common-continue") : import_utils.locales.getText("pisell-common-sign-up")
      )
    ), shouldShowDivider && /* @__PURE__ */ import_react.default.createElement("div", { className: "divider" }, /* @__PURE__ */ import_react.default.createElement("span", null, import_utils.locales.getText("pisell-common-or"))), /* @__PURE__ */ import_react.default.createElement("div", { className: "oauth-section" }, hasEmailAndPhone && /* @__PURE__ */ import_react.default.createElement(
      import_materials.Button,
      {
        type: "default",
        size: "large",
        block: true,
        onClick: () => handleSwitchAuthMethod(
          currentAuthMethod === "email" ? "phone" : "email"
        ),
        className: "login2-switch-button",
        icon: currentAuthMethod === "email" ? /* @__PURE__ */ import_react.default.createElement(import_materials2.Iconfont, { type: "pisell2-phone", className: "oauth-icon" }) : /* @__PURE__ */ import_react.default.createElement(import_materials2.Iconfont, { type: "pisell2-mail-01", className: "oauth-icon" }),
        style: { marginBottom: oauthProviders.length ? 12 : 0 }
      },
      currentAuthMethod === "email" ? import_utils.locales.getText("pisell-register2-with-phone") : import_utils.locales.getText("pisell-register2-with-email")
    ), /* @__PURE__ */ import_react.default.createElement(
      import_OAuthButtonGroup.default,
      {
        providers: oauthProviders,
        wrapperClassName: "oauth-buttons-container",
        buttonClassName: "oauth-button",
        layout: "vertical",
        gap: 12
      }
    ))),
    /* @__PURE__ */ import_react.default.createElement("div", { className: "login2-footer-text" }, import_utils.locales.getText("pisell-register2-have-account"), " ", /* @__PURE__ */ import_react.default.createElement("a", { className: "login2-link", onClick: onGoToLogin }, import_utils.locales.getText("pisell-register2-login-link"))),
    /* @__PURE__ */ import_react.default.createElement(import_LegalTerms.default, { config: { ...config.legalTerms, mode: "register" } })
  );
};
var Register2_default = Register2;
