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/Login2.tsx
var Login2_exports = {};
__export(Login2_exports, {
  default: () => Login2_default
});
module.exports = __toCommonJS(Login2_exports);
var import_react = __toESM(require("react"));
var import_antd = require("antd");
var import_materials = require("@pisell/materials");
var import_classnames = __toESM(require("classnames"));
var import_utils = require("@pisell/utils");
var import_ahooks = require("ahooks");
var import_locales = __toESM(require("./locales"));
var import_Header = __toESM(require("./shared/Header"));
var import_LoginCodeInput = __toESM(require("./components/LoginCodeInput"));
var import_ForgotPasswordFlow = __toESM(require("./components/ForgotPasswordFlow"));
var import_SetPassword = __toESM(require("./steps/SetPassword"));
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_materials2 = require("@pisell/materials");
var import_usePasswordValidationRules = __toESM(require("./hooks/usePasswordValidationRules"));
var import_OAuthButtonGroup = __toESM(require("./components/OAuthButtonGroup"));
var Login2 = ({
  config,
  visible = true,
  onClose,
  className,
  style,
  onLogin,
  onOAuthLogin,
  onSendVerificationCode,
  onForgotPassword,
  onSwitchToRegister,
  onError
}) => {
  var _a, _b, _c, _d, _e, _f;
  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 pisellOS = (0, import_useEngineContext.usePisellOS)();
  const registerAndLogin = pisellOS == null ? void 0 : pisellOS.getModule("registerAndLogin");
  const context = (0, import_useEngineContext2.default)();
  const storage = (_b = (_a = context == null ? void 0 : context.appHelper) == null ? void 0 : _a.utils) == null ? void 0 : _b.storage;
  const rememberMeWatch = import_antd.Form.useWatch("remember_me", form);
  (0, import_react.useEffect)(() => {
    if (typeof rememberMeWatch === "boolean" && !rememberMeWatch) {
      storage.remove("login_account");
      storage.remove("login_password");
    }
  }, [rememberMeWatch]);
  (0, import_react.useEffect)(() => {
    var _a2, _b2, _c2, _d2, _e2, _f2, _g;
    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)) || ((_g = (_f2 = context.appHelper.utils) == null ? void 0 : _f2.storage) == null ? void 0 : _g.get("umi_locale")) || "en"
    );
  }, []);
  const loginMethods = config.loginMethods || [];
  const passwordValidationRules = (0, import_usePasswordValidationRules.default)(
    (_c = config.ui) == null ? void 0 : _c.passwordRules,
    {
      translate: import_utils.locales.getText,
      fallbackMinLength: 6,
      messageKeys: {
        required: import_utils.locales.getText("pisell-login2-password-required"),
        minLength: import_utils.locales.getText("pisell-set-password-min-length"),
        requireUppercase: import_utils.locales.getText("pisell-set-password-require-uppercase"),
        requireLowercase: import_utils.locales.getText("pisell-set-password-require-lowercase"),
        requireNumber: import_utils.locales.getText("pisell-set-password-require-number"),
        requireSpecialCharacters: import_utils.locales.getText("pisell-set-password-require-special"),
        summary: import_utils.locales.getText("pisell-set-password-must-contain")
      }
    }
  );
  const [currentLoginMethod, setCurrentLoginMethod] = (0, import_react.useState)(null);
  const [currentVerificationMethod, setCurrentVerificationMethod] = (0, import_react.useState)("password");
  const hasTriggeredGuestLoginRef = (0, import_react.useRef)(false);
  (0, import_react.useEffect)(() => {
    var _a2;
    if (loginMethods.length > 0 && !currentLoginMethod) {
      const initialMethod = loginMethods[0];
      setCurrentLoginMethod(initialMethod);
      if ((initialMethod == null ? void 0 : initialMethod.type) === "email" || (initialMethod == null ? void 0 : initialMethod.type) === "phone") {
        setCurrentVerificationMethod(
          ((_a2 = initialMethod.verificationMethods) == null ? void 0 : _a2[0]) || "password"
        );
      }
    }
    if (hasTriggeredGuestLoginRef.current) return;
    const hasOnlyGuest = loginMethods.length === 1 && loginMethods[0].type === "guest";
    if (!hasOnlyGuest) return;
    hasTriggeredGuestLoginRef.current = true;
    handleGuestLogin();
  }, [loginMethods, currentLoginMethod]);
  (0, import_react.useEffect)(() => {
    if (((currentLoginMethod == null ? void 0 : currentLoginMethod.type) === "email" || (currentLoginMethod == null ? void 0 : currentLoginMethod.type) === "phone") && currentVerificationMethod === "password") {
      const storedRememberMe = storage.get("login_remember_me") === "true";
      setRememberMe(storedRememberMe);
      let account = storage.get("login_account");
      try {
        account = JSON.parse(account || "{}");
      } catch (e) {
        console.error(e);
      }
      if (account && storedRememberMe) {
        const accountString = typeof account === "string" ? account : account.phone || account.email || "";
        const isEmail = accountString.includes("@");
        const isPhone = /^\d+$/.test(accountString.replace(/\+/g, "").replace(/\s/g, ""));
        const shouldUseStoredAccount = currentLoginMethod.type === "email" && isEmail || currentLoginMethod.type === "phone" && isPhone;
        if (shouldUseStoredAccount) {
          setEnteredAccount(account);
          setHasStoredCredentials(true);
          if (isEmail && !form.getFieldValue("email")) {
            form.setFieldsValue({
              email: account
            });
          }
          if (isPhone && !form.getFieldValue("phone")) {
            form.setFieldsValue({
              phone: account
            });
          }
          if (currentLoginMethod == null ? void 0 : currentLoginMethod.stepByStep) {
            setLoginStep("password");
          }
        } else {
          setHasStoredCredentials(false);
          setEnteredAccount("");
        }
      } else {
        setHasStoredCredentials(false);
      }
    }
  }, [currentLoginMethod, currentVerificationMethod]);
  (0, import_react.useEffect)(() => {
    if (!visible) {
      form.setFieldsValue({ password: "" });
    }
  }, [visible, form]);
  const [loginStep, setLoginStep] = (0, import_react.useState)(
    "account"
  );
  const [enteredAccount, setEnteredAccount] = (0, import_react.useState)("");
  const [codeError, setCodeError] = (0, import_react.useState)("");
  const [rememberMe, setRememberMe] = (0, import_react.useState)(false);
  const [hasStoredCredentials, setHasStoredCredentials] = (0, import_react.useState)(false);
  const [lastLoginMethod, setLastLoginMethod] = (0, import_react.useState)(null);
  const [showForgotPassword, setShowForgotPassword] = (0, import_react.useState)(false);
  const [emailLinkVerifyStatus, setEmailLinkVerifyStatus] = (0, import_react.useState)(null);
  const [emailLinkError, setEmailLinkError] = (0, import_react.useState)("");
  const [resetPasswordUserEmail, setResetPasswordUserEmail] = (0, import_react.useState)("");
  const isEmailLinkVerification = ((_d = config.emailLinkVerification) == null ? void 0 : _d.enabled) && ((_e = config.emailLinkVerification) == null ? void 0 : _e.code);
  (0, import_react.useEffect)(() => {
    var _a2;
    if (isEmailLinkVerification && ((_a2 = config.emailLinkVerification) == null ? void 0 : _a2.code)) {
      setEmailLinkVerifyStatus("verifying");
      const checkCode = async () => {
        var _a3;
        try {
          if (registerAndLogin == null ? void 0 : registerAndLogin.checkResetPasswordCode) {
            const result = await registerAndLogin.checkResetPasswordCode({
              code: config.emailLinkVerification.code
            });
            if (result.status) {
              setEmailLinkVerifyStatus("success");
              if ((_a3 = result.data) == null ? void 0 : _a3.email) {
                setResetPasswordUserEmail(result.data.email);
              }
            } else {
              setEmailLinkVerifyStatus("error");
              setEmailLinkError(result.message || "验证码无效或已过期");
            }
          } else {
            setEmailLinkVerifyStatus("error");
            setEmailLinkError("系统错误，请稍后重试");
          }
        } catch (error) {
          setEmailLinkVerifyStatus("error");
          setEmailLinkError("网络错误，请稍后重试");
        }
      };
      checkCode();
    }
  }, [
    isEmailLinkVerification,
    (_f = config.emailLinkVerification) == null ? void 0 : _f.code,
    registerAndLogin
  ]);
  (0, import_react.useEffect)(() => {
    if (countdown > 0) {
      const timer = setTimeout(() => {
        setCountdown(countdown - 1);
      }, 1e3);
      return () => clearTimeout(timer);
    }
  }, [countdown]);
  (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)(() => {
    try {
      const storedLoginMethod = storage.get("pisell_last_login_method");
      if (storedLoginMethod) {
        const parsedMethod = JSON.parse(storedLoginMethod);
        setLastLoginMethod(parsedMethod);
      }
      const rememberMe2 = storage.get("login_remember_me") === "true";
      const account = storage.get("login_account");
      const password = storage.get("login_password");
      if (rememberMe2 && account && password) {
        let accountData;
        try {
          accountData = JSON.parse(account || "{}");
        } catch (e) {
          accountData = account;
        }
        const isEmail = typeof accountData === "string" && accountData.includes("@");
        const loginMethod = loginMethods.find((m) => m.type === (isEmail ? "email" : "phone"));
        if (loginMethod) {
          setCurrentLoginMethod(loginMethod);
          setCurrentVerificationMethod("password");
          setEnteredAccount(accountData);
          const accountFieldName = isEmail ? "email" : "phone";
          form.setFieldsValue({ [accountFieldName]: accountData, password, remember_me: true });
          setLoginStep("password");
          setRememberMe(true);
        }
      }
    } catch (error) {
      console.error("Failed to parse last login method:", error);
    }
  }, [loginMethods]);
  const isLastLoginMethod = (0, import_react.useCallback)((methodType) => {
    if (!lastLoginMethod) return false;
    return lastLoginMethod.type === methodType;
  }, [lastLoginMethod]);
  const switchVerificationMethod = (0, import_react.useCallback)(
    (method) => {
      form.resetFields();
      setLoginStep("account");
      setEnteredAccount("");
      setCurrentVerificationMethod(method);
    },
    [form]
  );
  const switchLoginMethod = (0, import_react.useCallback)(
    (method) => {
      form.resetFields();
      setLoginStep("account");
      setEnteredAccount("");
      setHasStoredCredentials(false);
      setCurrentLoginMethod(method);
      if (method.type === "email" || method.type === "phone") {
        setCurrentVerificationMethod(method.verificationMethods[0]);
      }
    },
    [form]
  );
  const handleContinueWithAccountInternal = async () => {
    var _a2, _b2, _c2, _d2, _e2, _f2, _g;
    try {
      setLoading(true);
      const accountFieldName = (currentLoginMethod == null ? void 0 : currentLoginMethod.type) === "email" ? "email" : "phone";
      const accountValues = await form.validateFields([accountFieldName]);
      const account = accountValues[accountFieldName];
      if ((currentLoginMethod == null ? void 0 : currentLoginMethod.type) === "email" && registerAndLogin) {
        const utils = ((_a2 = context == null ? void 0 : context.appHelper) == null ? void 0 : _a2.utils) || {};
        const shopId = ((_g = (_f2 = (_e2 = (_d2 = (_c2 = (_b2 = utils.getStore) == null ? void 0 : _b2.call(utils)) == null ? void 0 : _c2.getState) == null ? void 0 : _d2.call(_c2)) == null ? void 0 : _e2.global) == null ? void 0 : _f2.shop) == null ? void 0 : _g.id) || 9;
        const result = await registerAndLogin.checkEmailExists({
          email: account,
          shop_id: shopId
        });
        if (result.status && result.data) {
          if (result.data.exists) {
            setEnteredAccount(account);
            setLoginStep("password");
            form.setFieldsValue({ [accountFieldName]: account });
          } else {
            import_antd.message.error(
              import_utils.locales.getText("pisell-login2-email-not-registered")
            );
            return;
          }
        } else {
          import_antd.message.error(
            result.message || import_utils.locales.getText("pisell-login2-check-email-failed")
          );
          return;
        }
      } else {
        setEnteredAccount(account);
        setLoginStep("password");
        form.setFieldsValue({ [accountFieldName]: account });
      }
    } catch (error) {
      if (error.errorFields) {
        return;
      }
      console.error("Continue with account error:", error);
      import_antd.message.error(
        (error == null ? void 0 : error.message) || import_utils.locales.getText("pisell-login2-continue-failed")
      );
    } finally {
      setLoading(false);
    }
  };
  const { run: handleContinueWithAccount } = (0, import_ahooks.useDebounceFn)(handleContinueWithAccountInternal, {
    wait: 200,
    leading: true,
    trailing: false
  });
  const handleBackToAccountInternal = () => {
    setLoginStep("account");
    form.resetFields(["password"]);
  };
  const { run: handleBackToAccount } = (0, import_ahooks.useDebounceFn)(handleBackToAccountInternal, {
    wait: 200,
    leading: true,
    trailing: false
  });
  const handleSendCode = async () => {
    var _a2;
    try {
      const accountFieldName = (currentLoginMethod == null ? void 0 : currentLoginMethod.type) === "email" ? "email" : "phone";
      await form.validateFields([accountFieldName]);
      const account = form.getFieldValue(accountFieldName);
      if (!account) {
        import_antd.message.error(import_utils.locales.getText("pisell-login2-account-required"));
        return;
      }
      setLoading(true);
      const type = (currentLoginMethod == null ? void 0 : currentLoginMethod.type) === "email" ? "email" : "phone";
      if (registerAndLogin) {
        let res;
        if (type === "email") {
          res = await registerAndLogin.sendEmailLoginCode({
            type: "email",
            target: account,
            purpose: "login"
          });
        } else {
          let phoneData;
          if (typeof account === "string") {
            phoneData = {
              phone: account,
              country_calling_code: ((_a2 = countries.find((country) => country.value === account)) == null ? void 0 : _a2.calling_code) || ""
            };
          } else {
            phoneData = account;
          }
          res = await registerAndLogin.sendSmsLoginCode(phoneData);
        }
        if ((res == null ? void 0 : res.code) !== 200) {
          throw new Error(
            (res == null ? void 0 : res.message) || import_utils.locales.getText("pisell-login2-code-send-failed")
          );
        }
      }
      await (onSendVerificationCode == null ? void 0 : onSendVerificationCode(account, type, config.channel));
      setEnteredAccount(account);
      setLoginStep("code");
      setCountdown(60);
      import_antd.message.success(import_utils.locales.getText("pisell-login2-code-sent"));
    } catch (error) {
      if (error == null ? void 0 : error.errorFields) return;
      import_antd.message.error(
        (error == null ? void 0 : error.message) || import_utils.locales.getText("pisell-login2-code-send-failed")
      );
    } finally {
      setLoading(false);
    }
  };
  const handleCodeSubmit = async (code) => {
    var _a2;
    try {
      setLoading(true);
      setCodeError("");
      const method = (currentLoginMethod == null ? void 0 : currentLoginMethod.type) || "email";
      let result;
      if (registerAndLogin) {
        if (method === "email") {
          result = await registerAndLogin.emailCodeLogin({
            email: enteredAccount,
            code
          });
        } else if (method === "phone") {
          let phoneData;
          if (typeof enteredAccount === "string") {
            phoneData = {
              phone: enteredAccount,
              country_calling_code: ((_a2 = countries.find((country) => country.value === enteredAccount)) == null ? void 0 : _a2.calling_code) || ""
            };
          } else {
            phoneData = enteredAccount;
          }
          result = await registerAndLogin.phoneCodeLogin({
            phone: phoneData.phone,
            country_calling_code: phoneData.country_calling_code,
            code
          });
        }
        if ((result == null ? void 0 : result.code) !== 200) {
          const errorMessage = (result == null ? void 0 : result.message) || import_utils.locales.getText("pisell-login2-login-failed");
          const error = new Error(errorMessage);
          onError == null ? void 0 : onError(error, method);
          setCodeError(errorMessage);
          return;
        }
      }
      const loginData = {
        account: enteredAccount,
        password: void 0,
        verification_code: code,
        remember_me: false
      };
      await (onLogin == null ? void 0 : onLogin(result.data, method, loginData, config.channel));
      import_antd.message.success(import_utils.locales.getText("pisell-login2-login-success"));
    } catch (error) {
      setCodeError(
        (error == null ? void 0 : error.message) || import_utils.locales.getText("pisell-login2-login-failed")
      );
    } finally {
      setLoading(false);
    }
  };
  const handleBackFromCode = () => {
    setLoginStep("account");
    form.resetFields();
    setCodeError("");
  };
  const handleForgotPasswordClickInternal = () => {
    const accountFieldName = (currentLoginMethod == null ? void 0 : currentLoginMethod.type) === "email" ? "email" : "phone";
    const account = form.getFieldValue(accountFieldName);
    setEnteredAccount(account || "");
    setShowForgotPassword(true);
  };
  const { run: handleForgotPasswordClick } = (0, import_ahooks.useDebounceFn)(handleForgotPasswordClickInternal, {
    wait: 200,
    leading: true,
    trailing: false
  });
  const handleCloseForgotPassword = () => {
    setShowForgotPassword(false);
    setCountdown(0);
  };
  const handleForgotPasswordSendLink = async (account) => {
    try {
      setLoading(true);
      if (registerAndLogin) {
        const res = await registerAndLogin.sendResetPasswordLink({
          email: account
        });
        if (!res.status) {
          throw new Error(res.message || "发送重置密码链接失败");
        }
      }
      import_antd.message.success(import_utils.locales.getText("pisell-forgot-password-link-sent"));
    } catch (error) {
      import_antd.message.error((error == null ? void 0 : error.message) || "发送重置密码链接失败");
      throw error;
    } finally {
      setLoading(false);
    }
  };
  const handleForgotPasswordSendCode = async (account) => {
    try {
      setLoading(true);
      const type = (currentLoginMethod == null ? void 0 : currentLoginMethod.type) === "email" ? "email" : "phone";
      if (registerAndLogin) {
        if (type === "email") {
          const res = await registerAndLogin.sendPasswordResetEmail({
            email: account
          });
          if (!res.status) {
            throw new Error(
              res.message || import_utils.locales.getText("pisell-login2-code-send-failed")
            );
          }
        } else {
          const phoneAccount = account;
          const res = await registerAndLogin.sendPasswordResetSms({
            phone: phoneAccount.phone,
            country_calling_code: phoneAccount.country_calling_code
          });
          if (!res.status) {
            throw new Error(
              res.message || import_utils.locales.getText("pisell-login2-code-send-failed")
            );
          }
        }
      }
      setCountdown(60);
      import_antd.message.success(import_utils.locales.getText("pisell-login2-code-sent"));
    } catch (error) {
      import_antd.message.error(
        (error == null ? void 0 : error.message) || import_utils.locales.getText("pisell-login2-code-send-failed")
      );
      throw error;
    } finally {
      setLoading(false);
    }
  };
  const handleForgotPasswordVerifyCode = async (account, code) => {
    var _a2, _b2, _c2, _d2, _e2, _f2, _g;
    try {
      setLoading(true);
      if (registerAndLogin) {
        const utils = ((_a2 = context == null ? void 0 : context.appHelper) == null ? void 0 : _a2.utils) || {};
        const shopId = ((_g = (_f2 = (_e2 = (_d2 = (_c2 = (_b2 = utils.getStore) == null ? void 0 : _b2.call(utils)) == null ? void 0 : _c2.getState) == null ? void 0 : _d2.call(_c2)) == null ? void 0 : _e2.global) == null ? void 0 : _f2.shop) == null ? void 0 : _g.id) || 9;
        const isPhoneAccount = typeof account === "object" && "phone" in account;
        let res;
        if (!isPhoneAccount) {
          res = await registerAndLogin.checkEmailCode({
            email: account,
            shop_id: shopId,
            code,
            action: "customer_reset_password_code"
          });
        } else {
          const phoneData = account;
          res = await registerAndLogin.checkMobileCode({
            phone: phoneData.phone,
            country_calling_code: phoneData.country_calling_code,
            code,
            action: "forget"
          });
        }
        if (!res.status) {
          throw new Error(res.message || "验证码验证失败");
        }
        if (!res.data.valid) {
          throw new Error(import_utils.locales.getText("pisell-login2-code-verify-failed"));
        }
      }
    } catch (error) {
      import_antd.message.error((error == null ? void 0 : error.message) || "验证码验证失败");
      throw error;
    } finally {
      setLoading(false);
    }
  };
  const handleForgotPasswordReset = async (account, password, code) => {
    try {
      setLoading(true);
      if (registerAndLogin) {
        const isPhoneAccount2 = typeof account === "object" && "phone" in account;
        let resetPasswordParams;
        if (isPhoneAccount2) {
          resetPasswordParams = {
            type: "phone",
            target: {
              phone: account.phone,
              country_calling_code: account.country_calling_code
            },
            password,
            code
          };
        } else {
          resetPasswordParams = {
            type: "email",
            target: {
              email: account
            },
            password,
            code
          };
        }
        const res = await registerAndLogin.resetPassword(resetPasswordParams);
        if ((res == null ? void 0 : res.code) !== 200) {
          throw new Error((res == null ? void 0 : res.message) || import_utils.locales.getText("pisell-forgot-password-failed"));
        }
      }
      handleCloseForgotPassword();
      const isPhoneAccount = typeof account === "object" && "phone" in account;
      if (isPhoneAccount) {
        const phoneMethod = config.loginMethods.find((method) => method.type === "phone");
        if (phoneMethod) {
          setCurrentLoginMethod(phoneMethod);
          setCurrentVerificationMethod(phoneMethod.verificationMethods[0]);
        }
        form.setFieldsValue({ phone: account });
        setEnteredAccount(account);
      } else {
        const emailMethod = config.loginMethods.find((method) => method.type === "email");
        if (emailMethod) {
          setCurrentLoginMethod(emailMethod);
          setCurrentVerificationMethod(emailMethod.verificationMethods[0]);
        }
        form.setFieldsValue({ email: account });
        setEnteredAccount(account);
      }
      setLoginStep("account");
    } catch (error) {
      import_antd.message.error((error == null ? void 0 : error.message) || import_utils.locales.getText("pisell-forgot-password-failed"));
    } finally {
      setLoading(false);
    }
  };
  const handleEmailLinkResetPassword = async (account, password, code) => {
    try {
      setLoading(true);
      if (registerAndLogin) {
        const res = await registerAndLogin.resetPasswordByCode({
          code: config.emailLinkVerification.code,
          password
        });
        if ((res == null ? void 0 : res.code) !== 200) {
          throw new Error((res == null ? void 0 : res.message) || import_utils.locales.getText("pisell-forgot-password-failed"));
        }
      }
      handleCloseForgotPassword();
      setEmailLinkVerifyStatus(null);
      import_antd.message.success(import_utils.locales.getText("pisell-forgot-password-success"));
    } catch (error) {
      import_antd.message.error((error == null ? void 0 : error.message) || import_utils.locales.getText("pisell-forgot-password-failed"));
      throw error;
    } finally {
      setLoading(false);
    }
  };
  const handleGuestLoginInternal = async () => {
    try {
      setLoading(true);
      if (registerAndLogin) {
        const result = await registerAndLogin.guestLogin();
        if (result.code === 200) {
          import_antd.message.success(import_utils.locales.getText("pisell-login2-login-success"));
          const loginMethodInfo = {
            type: "guest",
            verificationMethod: null,
            timestamp: Date.now()
          };
          storage.set("pisell_last_login_method", JSON.stringify(loginMethodInfo));
          onLogin == null ? void 0 : onLogin(
            result.data,
            "guest",
            {
              account: "guest",
              password: void 0
            },
            config.channel
          );
        } else {
          import_antd.message.error(
            result.message || import_utils.locales.getText("pisell-login2-login-failed")
          );
        }
      }
    } catch (error) {
      console.error("Guest login error:", error);
      import_antd.message.error(import_utils.locales.getText("pisell-login2-login-failed"));
    } finally {
      setLoading(false);
    }
  };
  const { run: handleGuestLogin } = (0, import_ahooks.useDebounceFn)(handleGuestLoginInternal, {
    wait: 200,
    leading: true,
    trailing: false
  });
  const handleLoginInternal = async () => {
    var _a2;
    try {
      setLoading(true);
      const values = await form.validateFields();
      const accountFieldName = (currentLoginMethod == null ? void 0 : currentLoginMethod.type) === "email" ? "email" : "phone";
      const account = values[accountFieldName] || values.account;
      const loginData = {
        account,
        password: currentVerificationMethod === "password" ? values.password : void 0,
        verification_code: currentVerificationMethod === "verification_code" ? values.verification_code : void 0,
        remember_me: values.remember_me
      };
      const method = (currentLoginMethod == null ? void 0 : currentLoginMethod.type) || "email";
      let result;
      if (registerAndLogin) {
        if (method === "email") {
          if (currentVerificationMethod === "password") {
            result = await registerAndLogin.emailPasswordLogin({
              email: account,
              password: values.password
            });
          } else {
            result = await registerAndLogin.emailCodeLogin({
              email: account,
              code: values.verification_code
            });
          }
        } else if (method === "phone") {
          let phoneData;
          if (typeof account === "string") {
            phoneData = {
              phone: account,
              country_calling_code: ((_a2 = countries.find((country) => country.value === account)) == null ? void 0 : _a2.calling_code) || ""
            };
          } else {
            phoneData = account;
          }
          if (currentVerificationMethod === "password") {
            result = await registerAndLogin.phonePasswordLogin({
              phone: phoneData.phone,
              country_calling_code: phoneData.country_calling_code,
              password: values.password
            });
          } else {
            result = await registerAndLogin.phoneCodeLogin({
              phone: phoneData.phone,
              country_calling_code: phoneData.country_calling_code,
              code: values.verification_code
            });
          }
        }
        if ((result == null ? void 0 : result.code) !== 200) {
          throw new Error(
            (result == null ? void 0 : result.message) || import_utils.locales.getText("pisell-login2-login-failed")
          );
        }
      }
      await (onLogin == null ? void 0 : onLogin(result.data, method, loginData, config.channel));
      const loginMethodInfo = {
        type: method,
        verificationMethod: currentVerificationMethod,
        timestamp: Date.now()
      };
      storage.set("pisell_last_login_method", JSON.stringify(loginMethodInfo));
      if (values.remember_me && account) {
        storage.set("login_account", JSON.stringify(account));
        storage.set("login_remember_me", "true");
        if (currentVerificationMethod === "password") {
          storage.set("login_password", values.password);
        }
        setEnteredAccount(account);
      } else {
        storage.remove("login_account");
        storage.remove("login_remember_me");
        storage.remove("login_password");
      }
      import_antd.message.success(import_utils.locales.getText("pisell-login2-login-success"));
    } catch (error) {
      if (error.errorFields) {
        return;
      }
      import_antd.message.error(
        (error == null ? void 0 : error.message) || import_utils.locales.getText("pisell-login2-login-failed")
      );
    } finally {
      setLoading(false);
    }
  };
  const { run: handleLogin } = (0, import_ahooks.useDebounceFn)(handleLoginInternal, {
    wait: 1e3,
    leading: true,
    trailing: false
  });
  const handleOAuthClickInternal = async (provider) => {
    var _a2, _b2;
    try {
      setLoading(true);
      if (provider === "facebook") {
        const fbConfig = (_a2 = config == null ? void 0 : config.loginMethods) == null ? void 0 : _a2.find((n) => n.type === "facebook");
        const token = fbConfig == null ? void 0 : fbConfig.appId;
        if (token) {
          const res = await registerAndLogin.loginWithFacebook(token);
          if (res.status) {
            onLogin == null ? void 0 : onLogin(res.data, "facebook", { account: "", password: "" }, config.channel);
          }
        } else {
          throw new Error("Facebook app_id not configured");
        }
      } else if (provider === "apple") {
        const appleConfig = (_b2 = config == null ? void 0 : config.loginMethods) == 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);
          onLogin == null ? void 0 : onLogin(res.data, "apple", { account: "", password: "" }, config.channel);
        } else {
          throw new Error("Apple client_id not configured");
        }
      } else {
        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"));
      }
      import_antd.message.error(
        (error == null ? void 0 : error.message) || import_utils.locales.getText("pisell-login2-login-failed")
      );
    } finally {
      setLoading(false);
    }
  };
  const { run: handleOAuthClick } = (0, import_ahooks.useDebounceFn)(handleOAuthClickInternal, {
    wait: 200,
    leading: true,
    trailing: false
  });
  const oauthProviders = (0, import_react.useMemo)(() => {
    return loginMethods.filter(
      (method) => ["google", "facebook", "apple", "guest"].includes(method.type)
    ).map((method) => {
      const isLast = isLastLoginMethod(method.type);
      const commonConfig = {
        className: (0, import_classnames.default)("login2-oauth-button", method.type, {
          "has-last-login-badge": isLast
        }),
        badge: isLast ? import_utils.locales.getText("pisell-login2-last-login-badge") : void 0,
        badgeClassName: "last-login-badge"
      };
      switch (method.type) {
        case "google":
          return {
            key: "google",
            label: /* @__PURE__ */ import_react.default.createElement("span", null, import_utils.locales.getText("pisell-login2-continue-with"), " Google"),
            icon: /* @__PURE__ */ import_react.default.createElement(import_materials2.Iconfont, { type: "pisell2-google" }),
            onClick: () => handleOAuthClick("google"),
            ...commonConfig
          };
        case "facebook":
          return {
            key: "facebook",
            label: /* @__PURE__ */ import_react.default.createElement("span", null, import_utils.locales.getText("pisell-login2-continue-with"), " Facebook"),
            icon: /* @__PURE__ */ import_react.default.createElement(import_materials2.Iconfont, { type: "pisell2-facebook" }),
            onClick: () => handleOAuthClick("facebook"),
            ...commonConfig
          };
        case "apple":
          return {
            key: "apple",
            label: /* @__PURE__ */ import_react.default.createElement("span", null, import_utils.locales.getText("pisell-login2-continue-with"), " Apple"),
            icon: /* @__PURE__ */ import_react.default.createElement(import_materials2.Iconfont, { type: "pisell2-apple" }),
            onClick: () => handleOAuthClick("apple"),
            ...commonConfig
          };
        case "guest":
          return {
            key: "guest",
            label: import_utils.locales.getText("pisell-login2-login-as-guest"),
            icon: /* @__PURE__ */ import_react.default.createElement(import_materials2.Iconfont, { type: "pisell2-user-01" }),
            onClick: handleGuestLogin,
            ...commonConfig
          };
        default:
          return null;
      }
    }).filter(Boolean);
  }, [handleGuestLogin, handleOAuthClick, isLastLoginMethod, loginMethods]);
  const renderMainLoginForm = () => {
    var _a2, _b2, _c2, _d2, _e2, _f2, _g, _h, _i, _j, _k, _l, _m, _n, _o, _p, _q, _r, _s, _t, _u, _v, _w, _x, _y, _z;
    if (!currentLoginMethod) return null;
    const { type } = currentLoginMethod;
    if (type === "google" || type === "facebook" || type === "apple" || type === "guest") {
      return null;
    }
    const hasEmailOrPhoneMethod = loginMethods.some(
      (method) => method.type === "email" || method.type === "phone"
    );
    if (!hasEmailOrPhoneMethod) {
      return null;
    }
    const isEmail = type === "email";
    const isPhone = type === "phone";
    const accountFieldName = isEmail ? "email" : "phone";
    const getAccountValue = (values) => {
      if (values) {
        return values[accountFieldName] || values.account;
      }
      return form.getFieldValue(accountFieldName) || form.getFieldValue("account");
    };
    const accountLabel = isEmail ? ((_c2 = (_b2 = (_a2 = config.ui) == null ? void 0 : _a2.formLabels) == null ? void 0 : _b2.email) == null ? void 0 : _c2.show) !== false ? ((_f2 = (_e2 = (_d2 = config.ui) == null ? void 0 : _d2.formLabels) == null ? void 0 : _e2.email) == null ? void 0 : _f2.text) || import_utils.locales.getText("pisell-login2-email-label") : void 0 : ((_i = (_h = (_g = config.ui) == null ? void 0 : _g.formLabels) == null ? void 0 : _h.phone) == null ? void 0 : _i.show) !== false ? ((_l = (_k = (_j = config.ui) == null ? void 0 : _j.formLabels) == null ? void 0 : _k.phone) == null ? void 0 : _l.text) || import_utils.locales.getText("pisell-login2-phone-label") : void 0;
    const accountPlaceholder = isEmail ? import_utils.locales.getText("pisell-login2-email-placeholder") : import_utils.locales.getText("pisell-login2-phone-placeholder");
    const accountRules = isEmail ? [
      {
        required: true,
        message: import_utils.locales.getText("pisell-login2-email-required")
      },
      {
        type: "email",
        message: import_utils.locales.getText("pisell-login2-email-invalid")
      }
    ] : (0, import_phoneValidation.createPhoneValidationRules)(import_utils.locales.getText, true);
    const useStepByStep = (currentLoginMethod == null ? void 0 : currentLoginMethod.stepByStep) && currentVerificationMethod === "password";
    if (useStepByStep) {
      const isPasswordStep = loginStep === "password";
      const showPasswordField = isPasswordStep;
      const handleFormSubmit = (e) => {
        e == null ? void 0 : e.preventDefault();
        if (isPasswordStep) {
          handleLogin();
        } else {
          handleContinueWithAccount();
        }
      };
      return /* @__PURE__ */ import_react.default.createElement(
        import_antd.Form,
        {
          form,
          layout: "vertical",
          className: "login2-form",
          size: "large"
        },
        (isEmail || isPhone) && !showPasswordField && /* @__PURE__ */ import_react.default.createElement("div", { style: { position: "absolute", left: "-9999px", opacity: 0, pointerEvents: "none" } }, /* @__PURE__ */ import_react.default.createElement(
          "input",
          {
            type: "text",
            name: "username",
            autoComplete: "username",
            tabIndex: -1,
            readOnly: true,
            "aria-hidden": "true"
          }
        )),
        showPasswordField && /* @__PURE__ */ import_react.default.createElement("div", { className: "login2-account-show-text-edit" }, /* @__PURE__ */ import_react.default.createElement("span", { className: "login2-account-show-text-edit-text" }, isPhone && `+${(_m = getAccountValue()) == null ? void 0 : _m.country_calling_code}${(_n = getAccountValue()) == null ? void 0 : _n.phone}` || "", isEmail && getAccountValue() || ""), /* @__PURE__ */ import_react.default.createElement("span", { className: "login2-account-show-text-edit-icon", onClick: handleBackToAccount }, /* @__PURE__ */ import_react.default.createElement(import_materials2.Iconfont, { type: "pisell2-edit-05" }))),
        /* @__PURE__ */ import_react.default.createElement(
          import_antd.Form.Item,
          {
            style: { display: showPasswordField ? "none" : "block" },
            label: accountLabel,
            name: isEmail ? "email" : "phone",
            rules: accountRules,
            validateTrigger: ["onBlur", "onSubmit"],
            className: isPhone ? "phone-input-form-item" : ""
          },
          isPhone ? /* @__PURE__ */ import_react.default.createElement(
            import_PhoneInput.default,
            {
              size: "large",
              placeholder: accountPlaceholder,
              className: "login2-phone-input",
              countries,
              valueFormat: "object",
              value: isPasswordStep ? enteredAccount : getAccountValue() || void 0,
              onChange: (value) => {
                if (isPasswordStep) {
                  setEnteredAccount(value);
                }
                form.setFieldsValue({ [accountFieldName]: value });
              }
            }
          ) : /* @__PURE__ */ import_react.default.createElement(
            import_materials.Input,
            {
              size: "large",
              placeholder: accountPlaceholder,
              className: "login2-input",
              type: "email",
              autoComplete: "email",
              value: getAccountValue() || enteredAccount || "",
              onChange: (e) => {
                const newValue = e.target.value;
                if (isPasswordStep) {
                  setEnteredAccount(newValue);
                }
                form.setFieldsValue({ [accountFieldName]: newValue });
              },
              onKeyDown: (e) => {
                if (e.key === "Enter" && !e.shiftKey && !e.ctrlKey && !e.metaKey) {
                  e.preventDefault();
                  handleFormSubmit(e);
                }
              }
            }
          )
        ),
        /* @__PURE__ */ import_react.default.createElement(
          import_antd.Form.Item,
          {
            style: { display: showPasswordField ? "block" : "none" },
            label: ((_q = (_p = (_o = config.ui) == null ? void 0 : _o.formLabels) == null ? void 0 : _p.password) == null ? void 0 : _q.show) !== false ? ((_t = (_s = (_r = config.ui) == null ? void 0 : _r.formLabels) == null ? void 0 : _s.password) == null ? void 0 : _t.text) || import_utils.locales.getText("pisell-login2-password-label") : void 0,
            name: "password",
            validateTrigger: ["onBlur", "onSubmit"],
            rules: passwordValidationRules
          },
          /* @__PURE__ */ import_react.default.createElement(
            import_materials.Input.Password,
            {
              size: "large",
              placeholder: import_utils.locales.getText(
                "pisell-login2-password-placeholder"
              ),
              className: "login2-input",
              name: "password",
              autoComplete: "current-password",
              type: "password",
              autoFocus: hasStoredCredentials,
              onKeyDown: (e) => {
                if (e.key === "Enter" && !e.shiftKey && !e.ctrlKey && !e.metaKey) {
                  e.preventDefault();
                  handleFormSubmit(e);
                }
              }
            }
          )
        ),
        showPasswordField && /* @__PURE__ */ import_react.default.createElement("div", { className: "login2-form-footer" }, /* @__PURE__ */ import_react.default.createElement(import_antd.Form.Item, { name: "remember_me", valuePropName: "checked", noStyle: true }, /* @__PURE__ */ import_react.default.createElement(import_materials.Checkbox, { defaultChecked: rememberMe }, import_utils.locales.getText("pisell-login2-remember-me"))), /* @__PURE__ */ import_react.default.createElement("a", { className: "login2-link", onClick: handleForgotPasswordClick }, import_utils.locales.getText("pisell-login2-forgot-password"))),
        /* @__PURE__ */ import_react.default.createElement(
          import_antd.ConfigProvider,
          {
            theme: {
              token: {
                colorPrimary: (ui == null ? void 0 : ui.themeColor) || "#7F56D9"
              }
            }
          },
          /* @__PURE__ */ import_react.default.createElement(
            import_materials.Button,
            {
              type: "primary",
              size: "large",
              block: true,
              htmlType: "button",
              loading,
              onClick: handleFormSubmit,
              className: "login2-submit-button"
            },
            isPasswordStep ? import_utils.locales.getText("pisell-login2-login-button") : isEmail ? import_utils.locales.getText("pisell-login2-continue-with-email") : import_utils.locales.getText("pisell-login2-continue-with-phone")
          )
        ),
        showPasswordField && /* @__PURE__ */ import_react.default.createElement(
          import_materials.Button,
          {
            size: "large",
            block: true,
            onClick: handleBackToAccount,
            className: "login2-back-button"
          },
          import_utils.locales.getText("pisell-login2-back")
        )
      );
    }
    if (currentVerificationMethod === "verification_code" && loginStep === "account") {
      const handleFormSubmit = (e) => {
        e == null ? void 0 : e.preventDefault();
        handleSendCode();
      };
      return /* @__PURE__ */ import_react.default.createElement(
        import_antd.Form,
        {
          form,
          layout: "vertical",
          className: "login2-form",
          size: "large"
        },
        isEmail && /* @__PURE__ */ import_react.default.createElement("div", { style: { position: "absolute", left: "-9999px", opacity: 0, pointerEvents: "none" } }, /* @__PURE__ */ import_react.default.createElement(
          "input",
          {
            type: "text",
            name: "username",
            autoComplete: "username",
            tabIndex: -1,
            readOnly: true,
            "aria-hidden": "true"
          }
        )),
        /* @__PURE__ */ import_react.default.createElement(
          import_antd.Form.Item,
          {
            label: accountLabel,
            name: accountFieldName,
            rules: accountRules,
            className: isPhone ? "phone-input-form-item" : "",
            validateTrigger: ["onBlur", "onSubmit"]
          },
          isPhone ? /* @__PURE__ */ import_react.default.createElement(
            import_PhoneInput.default,
            {
              size: "large",
              placeholder: accountPlaceholder,
              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: accountPlaceholder,
              className: "login2-input",
              type: "email",
              autoComplete: "email",
              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"
          },
          isEmail ? import_utils.locales.getText("pisell-login2-continue-with-email") : import_utils.locales.getText("pisell-login2-continue-with-phone")
        )
      );
    }
    return /* @__PURE__ */ import_react.default.createElement(
      import_antd.Form,
      {
        form,
        layout: "vertical",
        className: "login2-form",
        size: "large",
        onFinish: handleLogin
      },
      isEmail && /* @__PURE__ */ import_react.default.createElement("div", { style: { position: "absolute", left: "-9999px", opacity: 0, pointerEvents: "none" } }, /* @__PURE__ */ import_react.default.createElement(
        "input",
        {
          type: "text",
          name: "username",
          autoComplete: "username",
          tabIndex: -1,
          readOnly: true,
          "aria-hidden": "true"
        }
      )),
      isEmail ? /* @__PURE__ */ import_react.default.createElement(import_antd.Form.Item, { label: accountLabel, name: accountFieldName, rules: accountRules, validateTrigger: ["onBlur", "onSubmit"] }, /* @__PURE__ */ import_react.default.createElement(
        import_materials.Input,
        {
          size: "large",
          placeholder: accountPlaceholder,
          className: "login2-input",
          type: "email",
          autoComplete: "email",
          value: getAccountValue() || enteredAccount || "",
          onChange: (e) => {
            const newValue = e.target.value;
            setEnteredAccount(newValue);
            form.setFieldsValue({ [accountFieldName]: newValue });
          }
        }
      )) : /* @__PURE__ */ import_react.default.createElement(import_antd.Form.Item, { label: accountLabel, name: accountFieldName, rules: accountRules, validateTrigger: ["onBlur", "onSubmit"] }, /* @__PURE__ */ import_react.default.createElement(
        import_PhoneInput.default,
        {
          size: "large",
          placeholder: accountPlaceholder,
          className: "login2-phone-input",
          countries,
          valueFormat: "object"
        }
      )),
      /* @__PURE__ */ import_react.default.createElement(
        import_antd.Form.Item,
        {
          label: ((_w = (_v = (_u = config.ui) == null ? void 0 : _u.formLabels) == null ? void 0 : _v.password) == null ? void 0 : _w.show) !== false ? ((_z = (_y = (_x = config.ui) == null ? void 0 : _x.formLabels) == null ? void 0 : _y.password) == null ? void 0 : _z.text) || import_utils.locales.getText("pisell-login2-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-login2-password-placeholder"),
            className: "login2-input",
            name: "password",
            autoComplete: "current-password",
            type: "password"
          }
        )
      ),
      /* @__PURE__ */ import_react.default.createElement("div", { className: "login2-form-footer" }, /* @__PURE__ */ import_react.default.createElement(import_antd.Form.Item, { name: "remember_me", valuePropName: "checked", noStyle: true }, /* @__PURE__ */ import_react.default.createElement(import_materials.Checkbox, null, import_utils.locales.getText("pisell-login2-remember-me"))), currentVerificationMethod === "password" && /* @__PURE__ */ import_react.default.createElement("a", { className: "login2-link", onClick: handleForgotPasswordClick }, import_utils.locales.getText("pisell-login2-forgot-password"))),
      /* @__PURE__ */ import_react.default.createElement(
        import_materials.Button,
        {
          type: "primary",
          size: "large",
          block: true,
          htmlType: "submit",
          loading,
          onClick: handleLogin,
          className: "login2-submit-button"
        },
        import_utils.locales.getText("pisell-login2-login-button")
      )
    );
  };
  const renderSwitchOptions = () => {
    if (!currentLoginMethod) return null;
    const primaryMethod = loginMethods[0];
    const currentIsFormMethod = currentLoginMethod.type === "email" || currentLoginMethod.type === "phone";
    const primaryIsFormMethod = (primaryMethod == null ? void 0 : primaryMethod.type) === "email" || (primaryMethod == null ? void 0 : primaryMethod.type) === "phone";
    const shouldUseFormLayout = currentIsFormMethod || primaryIsFormMethod;
    const verificationSwitchButtons = [];
    if (currentIsFormMethod) {
      (currentLoginMethod.verificationMethods || []).filter((method) => method !== currentVerificationMethod).forEach((method) => {
        if (method === "verification_code") {
          const text = currentLoginMethod.type === "email" ? import_utils.locales.getText("pisell-login2-switch-to-email-code") : import_utils.locales.getText("pisell-login2-switch-to-sms-code");
          verificationSwitchButtons.push(
            /* @__PURE__ */ import_react.default.createElement(
              "button",
              {
                key: "switch-to-code",
                className: "login2-switch-option-button",
                onClick: () => switchVerificationMethod("verification_code")
              },
              currentLoginMethod.type === "email" ? /* @__PURE__ */ import_react.default.createElement(import_materials2.Iconfont, { type: "pisell2-mail-01" }) : /* @__PURE__ */ import_react.default.createElement(import_materials2.Iconfont, { type: "pisell2-phone" }),
              /* @__PURE__ */ import_react.default.createElement("span", { className: "option-text" }, text)
            )
          );
        } else {
          verificationSwitchButtons.push(
            /* @__PURE__ */ import_react.default.createElement(
              "button",
              {
                key: "switch-to-password",
                className: "login2-switch-option-button",
                onClick: () => switchVerificationMethod("password")
              },
              /* @__PURE__ */ import_react.default.createElement(import_materials2.Iconfont, { type: "pisell2-key-01" }),
              /* @__PURE__ */ import_react.default.createElement("span", { className: "option-text" }, import_utils.locales.getText("pisell-login2-switch-to-password"))
            )
          );
        }
      });
    }
    const emailPhoneSwitchButtons = [];
    loginMethods.forEach((method, index) => {
      if (method.type === "email" || method.type === "phone") {
        if (method.type === currentLoginMethod.type) return;
        const isLast = isLastLoginMethod(method.type);
        const className2 = (0, import_classnames.default)("login2-switch-option-button", {
          "has-last-login-badge": isLast
        });
        emailPhoneSwitchButtons.push(
          /* @__PURE__ */ import_react.default.createElement(
            "button",
            {
              key: `${method.type}-${index}`,
              className: className2,
              onClick: () => switchLoginMethod(method)
            },
            isLast && /* @__PURE__ */ import_react.default.createElement("div", { className: "last-login-badge" }, import_utils.locales.getText("pisell-login2-last-login-badge")),
            /* @__PURE__ */ import_react.default.createElement(
              import_materials2.Iconfont,
              {
                type: method.type === "email" ? "pisell2-mail-01" : "pisell2-phone"
              }
            ),
            /* @__PURE__ */ import_react.default.createElement("span", { className: "option-text" }, method.type === "email" ? import_utils.locales.getText("pisell-login2-switch-to-email") : import_utils.locales.getText("pisell-login2-switch-to-phone"))
          )
        );
      }
    });
    const nonOauthButtons = [
      ...verificationSwitchButtons,
      ...emailPhoneSwitchButtons
    ];
    const registerPrompt = onSwitchToRegister && /* @__PURE__ */ import_react.default.createElement("div", { className: "login2-register-prompt" }, /* @__PURE__ */ import_react.default.createElement("span", { className: "register-prompt-text" }, import_utils.locales.getText("pisell-login2-no-account")), /* @__PURE__ */ import_react.default.createElement(
      "button",
      {
        className: "register-prompt-link",
        onClick: onSwitchToRegister
      },
      import_utils.locales.getText("pisell-login2-register-link")
    ));
    if (!nonOauthButtons.length && !oauthProviders.length) {
      return registerPrompt;
    }
    if (shouldUseFormLayout) {
      const groups = [];
      if (nonOauthButtons.length > 0) {
        groups.push(
          /* @__PURE__ */ import_react.default.createElement("div", { key: "non-oauth", className: "login2-switch-options" }, nonOauthButtons)
        );
      }
      if (oauthProviders.length > 0) {
        groups.push(
          /* @__PURE__ */ import_react.default.createElement(
            import_OAuthButtonGroup.default,
            {
              key: "oauth",
              providers: oauthProviders,
              wrapperClassName: "login2-oauth-buttons",
              buttonClassName: "login2-oauth-button",
              gap: 12
            }
          )
        );
      }
      if (!groups.length) {
        return registerPrompt;
      }
      return /* @__PURE__ */ import_react.default.createElement(import_react.default.Fragment, null, /* @__PURE__ */ import_react.default.createElement("div", { className: "login2-divider" }, import_utils.locales.getText("pisell-login2-or")), /* @__PURE__ */ import_react.default.createElement("div", { className: "login2-switch-groups" }, groups), registerPrompt);
    }
    const primaryProvider = oauthProviders.find(
      (provider) => provider.key === (primaryMethod == null ? void 0 : primaryMethod.type)
    );
    const secondaryOauthProviders = oauthProviders.filter(
      (provider) => provider.key !== (primaryMethod == null ? void 0 : primaryMethod.type)
    );
    const hasSecondaryButtons = nonOauthButtons.length > 0 || secondaryOauthProviders.length > 0;
    return /* @__PURE__ */ import_react.default.createElement(import_react.default.Fragment, null, /* @__PURE__ */ import_react.default.createElement("div", { className: "login2-switch-groups" }, primaryProvider ? /* @__PURE__ */ import_react.default.createElement(
      import_OAuthButtonGroup.default,
      {
        providers: [primaryProvider],
        wrapperClassName: "login2-oauth-buttons",
        buttonClassName: "login2-oauth-button",
        gap: 12
      }
    ) : /* @__PURE__ */ import_react.default.createElement("div", { className: "login2-switch-options" }, /* @__PURE__ */ import_react.default.createElement(
      "button",
      {
        key: "primary-fallback",
        className: "login2-switch-option-button",
        onClick: () => {
          if ((primaryMethod == null ? void 0 : primaryMethod.type) === "guest") {
            handleGuestLogin();
          } else if ((primaryMethod == null ? void 0 : primaryMethod.type) === "google" || (primaryMethod == null ? void 0 : primaryMethod.type) === "facebook" || (primaryMethod == null ? void 0 : primaryMethod.type) === "apple") {
            handleOAuthClick(primaryMethod.type);
          }
        }
      },
      /* @__PURE__ */ import_react.default.createElement(
        import_materials2.Iconfont,
        {
          type: (primaryMethod == null ? void 0 : primaryMethod.type) === "guest" ? "pisell2-user-01" : (primaryMethod == null ? void 0 : primaryMethod.type) === "google" ? "pisell2-google" : (primaryMethod == null ? void 0 : primaryMethod.type) === "facebook" ? "pisell2-facebook" : "pisell2-apple"
        }
      ),
      /* @__PURE__ */ import_react.default.createElement("span", { className: "option-text" }, (primaryMethod == null ? void 0 : primaryMethod.type) === "guest" ? import_utils.locales.getText("pisell-login2-login-as-guest") : `${import_utils.locales.getText("pisell-login2-continue-with")} ${(primaryMethod == null ? void 0 : primaryMethod.type) ? primaryMethod.type.charAt(0).toUpperCase() + primaryMethod.type.slice(1) : ""}`)
    )), hasSecondaryButtons && /* @__PURE__ */ import_react.default.createElement(import_react.default.Fragment, null, /* @__PURE__ */ import_react.default.createElement("div", { className: "login2-divider" }, import_utils.locales.getText("pisell-login2-or")), nonOauthButtons.length > 0 && /* @__PURE__ */ import_react.default.createElement("div", { className: "login2-switch-options" }, nonOauthButtons), secondaryOauthProviders.length > 0 && /* @__PURE__ */ import_react.default.createElement(
      import_OAuthButtonGroup.default,
      {
        providers: secondaryOauthProviders,
        wrapperClassName: "login2-oauth-buttons",
        buttonClassName: "login2-oauth-button",
        gap: 12
      }
    ))), registerPrompt);
  };
  if (!visible) {
    return null;
  }
  const { ui } = config;
  if (isEmailLinkVerification) {
    if (emailLinkVerifyStatus === "verifying") {
      return /* @__PURE__ */ import_react.default.createElement(
        "div",
        {
          className: (0, import_classnames.default)("login2-container", className),
          style: {
            ...style,
            "--theme-color": (ui == null ? void 0 : ui.themeColor) || "#7F56D9"
          }
        },
        /* @__PURE__ */ import_react.default.createElement("div", { className: "login2-email-link-verifying" }, /* @__PURE__ */ import_react.default.createElement("div", { className: "verifying-content" }, /* @__PURE__ */ import_react.default.createElement("div", { className: "verifying-icon" }, /* @__PURE__ */ import_react.default.createElement(import_materials2.Iconfont, { type: "icon-loading", spin: true })), /* @__PURE__ */ import_react.default.createElement("h2", { className: "verifying-title" }, "Verifying your email..."), /* @__PURE__ */ import_react.default.createElement("p", { className: "verifying-desc" }, "Please wait while we verify your email link.")))
      );
    }
    if (emailLinkVerifyStatus === "success") {
      return /* @__PURE__ */ import_react.default.createElement(
        "div",
        {
          className: (0, import_classnames.default)("login2-container", className),
          style: {
            ...style,
            "--theme-color": (ui == null ? void 0 : ui.themeColor) || "#7F56D9"
          }
        },
        /* @__PURE__ */ import_react.default.createElement(
          import_SetPassword.default,
          {
            scenario: "reset",
            flowData: {
              account: resetPasswordUserEmail || "",
              accountType: "email",
              verificationMethod: "verification_code"
            },
            onSubmit: async (password, confirmPassword) => {
              try {
                if (registerAndLogin == null ? void 0 : registerAndLogin.resetPasswordByCode) {
                  const result = await registerAndLogin.resetPasswordByCode({
                    code: config.emailLinkVerification.code,
                    password
                  });
                  if (result.status) {
                    import_antd.message.success(import_utils.locales.getText("pisell-forgot-password-success"));
                    setEmailLinkVerifyStatus(null);
                    setEmailLinkError("");
                    if (resetPasswordUserEmail) {
                      const emailMethod = config.loginMethods.find((method) => method.type === "email");
                      if (emailMethod) {
                        setCurrentLoginMethod(emailMethod);
                        setCurrentVerificationMethod(emailMethod.verificationMethods[0]);
                      }
                      form.setFieldsValue({ email: resetPasswordUserEmail });
                      setEnteredAccount(resetPasswordUserEmail);
                      setLoginStep("account");
                    }
                  } else {
                    import_antd.message.error(result.message || import_utils.locales.getText("pisell-forgot-password-failed"));
                  }
                } else {
                  import_antd.message.error("系统错误，请稍后重试");
                }
              } catch (error) {
                import_antd.message.error((error == null ? void 0 : error.message) || import_utils.locales.getText("pisell-forgot-password-failed"));
              }
            },
            onBack: () => {
              setEmailLinkVerifyStatus(null);
              setEmailLinkError("");
            },
            loading
          }
        )
      );
    }
    if (emailLinkVerifyStatus === "error") {
      return /* @__PURE__ */ import_react.default.createElement(
        "div",
        {
          className: (0, import_classnames.default)("login2-container", className),
          style: {
            ...style,
            "--theme-color": (ui == null ? void 0 : ui.themeColor) || "#7F56D9"
          }
        },
        /* @__PURE__ */ import_react.default.createElement("div", { className: "login2-email-link-error" }, /* @__PURE__ */ import_react.default.createElement("div", { className: "error-content" }, /* @__PURE__ */ import_react.default.createElement("div", { className: "error-icon" }, /* @__PURE__ */ import_react.default.createElement(import_materials2.Iconfont, { type: "icon-error" })), /* @__PURE__ */ import_react.default.createElement("h2", { className: "error-title" }, import_utils.locales.getText("pisell-login2-verification-failed-title")), /* @__PURE__ */ import_react.default.createElement("p", { className: "error-desc" }, emailLinkError), /* @__PURE__ */ import_react.default.createElement(
          import_materials.Button,
          {
            type: "primary",
            size: "large",
            block: true,
            className: "login2-error-main-button",
            onClick: () => {
              setEmailLinkVerifyStatus(null);
              setEmailLinkError("");
            }
          },
          import_utils.locales.getText("pisell-login2-login-button")
        )))
      );
    }
  }
  if (showForgotPassword) {
    const accountType = (currentLoginMethod == null ? void 0 : currentLoginMethod.type) === "email" ? "email" : "phone";
    return /* @__PURE__ */ import_react.default.createElement(
      "div",
      {
        className: (0, import_classnames.default)("login2-container", className),
        style: {
          ...style,
          "--theme-color": (ui == null ? void 0 : ui.themeColor) || "#7F56D9"
        }
      },
      /* @__PURE__ */ import_react.default.createElement(
        import_ForgotPasswordFlow.default,
        {
          initialEmail: enteredAccount,
          accountType,
          onSendCode: handleForgotPasswordSendCode,
          onVerifyCode: handleForgotPasswordVerifyCode,
          onResetPassword: isEmailLinkVerification ? handleEmailLinkResetPassword : handleForgotPasswordReset,
          onSendResetLink: handleForgotPasswordSendLink,
          onBack: handleCloseForgotPassword,
          loading,
          countdown,
          countries
        }
      )
    );
  }
  if (loginStep === "code") {
    const accountType = (currentLoginMethod == null ? void 0 : currentLoginMethod.type) === "email" ? "email" : "phone";
    return /* @__PURE__ */ import_react.default.createElement(
      "div",
      {
        className: (0, import_classnames.default)("login2-container", className),
        style: {
          ...style,
          "--theme-color": (ui == null ? void 0 : ui.themeColor) || "#7F56D9"
        }
      },
      /* @__PURE__ */ import_react.default.createElement(
        import_LoginCodeInput.default,
        {
          account: typeof enteredAccount === "string" ? enteredAccount : enteredAccount.phone,
          accountType,
          codeLength: 4,
          onSubmit: handleCodeSubmit,
          onResend: handleSendCode,
          onBack: handleBackFromCode,
          countdown,
          loading,
          error: codeError,
          onClearError: () => setCodeError("")
        }
      )
    );
  }
  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" }, renderMainLoginForm(), renderSwitchOptions()),
    /* @__PURE__ */ import_react.default.createElement(import_LegalTerms.default, { config: { ...config.legalTerms, mode: "login" } })
  );
};
var Login2_default = Login2;
