import _objectSpread from '@babel/runtime/helpers/objectSpread2';
import HCaptcha from '@hcaptcha/react-hcaptcha';
import { AUTH_CONNECTION } from '@web3auth/auth';
import { WALLET_CONNECTORS, ANALYTICS_EVENTS, log, WalletLoginError } from '@web3auth/no-modal';
import { useContext, useState, useRef, useEffect, useMemo, useCallback } from 'react';
import { useTranslation } from 'react-i18next';
import { capitalizeFirstLetter, CAPTCHA_SITE_KEY } from '../../config.js';
import { DEFAULT_LOGO_DARK, DEFAULT_LOGO_LIGHT } from '../../constants.js';
import { AnalyticsContext } from '../../context/AnalyticsContext.js';
import { RootContext } from '../../context/RootContext.js';
import { createPasswordlessHandler } from '../../handlers/factory.js';
import { isTestAccountPattern } from '../../helper/testAccounts.js';
import i18nInstance from '../../localeImport.js';
import { cn, getUserCountry, getIcons, validatePhoneNumber } from '../../utils.js';
import Image from '../Image/Image.js';
import SocialLoginList from '../SocialLoginList/SocialLoginList.js';
import LoginOtp from './LoginOtp/LoginOtp.js';
import LoginPasswordLess from './LoginPasswordLess/LoginPasswordLess.js';
import { jsx, jsxs } from 'react/jsx-runtime';

const restrictedLoginMethods = [AUTH_CONNECTION.SMS_PASSWORDLESS, AUTH_CONNECTION.EMAIL_PASSWORDLESS, AUTH_CONNECTION.AUTHENTICATOR, AUTH_CONNECTION.PASSKEYS, AUTH_CONNECTION.TELEGRAM, AUTH_CONNECTION.CUSTOM];
function Login(props) {
  // TODO: add appName, isEmailPrimary, isExternalPrimary
  const {
    web3authClientId,
    web3authNetwork,
    authBuildEnv,
    appLogo,
    isModalVisible,
    handleSocialLoginHeight,
    socialLoginsConfig,
    installedExternalWalletConfig,
    isDark,
    handleSocialLoginClick,
    totalExternalWallets,
    isEmailPasswordLessLoginVisible,
    isSmsPasswordLessLoginVisible,
    handleExternalWalletBtnClick,
    handleExternalWalletClick,
    areSocialLoginsVisible,
    showPasswordLessInput,
    showExternalWalletButton,
    showExternalWalletCount,
    showInstalledExternalWallets,
    logoAlignment = "center",
    buttonRadius = "pill",
    deviceDetails
  } = props;
  const [t] = useTranslation(undefined, {
    i18n: i18nInstance
  });
  const {
    bodyState,
    setBodyState
  } = useContext(RootContext);
  const {
    analytics
  } = useContext(AnalyticsContext);
  const [countryCode, setCountryCode] = useState("");
  const [countryFlag, setCountryFlag] = useState("");
  const [passwordlessErrorMessage, setPasswordlessErrorMessage] = useState("");
  const [otpErrorMessage, setOtpErrorMessage] = useState("");
  const [expandSocialLogins, setExpandSocialLogins] = useState(false);
  const [canShowMore, setCanShowMore] = useState(false);
  const [visibleRow, setVisibleRow] = useState([]);
  const [otherRow, setOtherRow] = useState([]);
  const [isPasswordLessCtaClicked, setIsPasswordLessCtaClicked] = useState(false);
  const [showOtpFlow, setShowOtpFlow] = useState(false);
  const [authConnection, setAuthConnection] = useState(undefined);
  const [passwordlessHandler, setPasswordlessHandler] = useState(undefined);
  const [isPasswordLessLoading, setIsPasswordLessLoading] = useState(false);
  const [otpLoading, setOtpLoading] = useState(false);
  const [showCaptcha, setShowCaptcha] = useState(false);
  const [captchaError, setCaptchaError] = useState("");
  const captchaRef = useRef(null);
  const handleSocialLoginExpand = () => {
    setExpandSocialLogins(prev => !prev);
    setIsPasswordLessCtaClicked(false);
    handleSocialLoginHeight();
  };
  useEffect(() => {
    const maxOptions = Object.keys(socialLoginsConfig.loginMethods).filter(loginMethodKey => {
      return socialLoginsConfig.loginMethods[loginMethodKey].showOnModal && !restrictedLoginMethods.includes(loginMethodKey);
    });
    const visibleRows = [];
    const otherRows = [];
    const loginMethodsOrder = (socialLoginsConfig.loginMethodsOrder || []).reduce((acc, method, index) => {
      acc[method] = index;
      return acc;
    }, {});
    const loginOptions = Object.keys(socialLoginsConfig.loginMethods).filter(method => {
      return !socialLoginsConfig.loginMethods[method].showOnModal === false && !restrictedLoginMethods.includes(method);
    }).sort((a, b) => {
      var _loginMethodsOrder$a, _loginMethodsOrder$b;
      const maxOrder = (socialLoginsConfig.loginMethodsOrder || []).length;
      const aOrder = (_loginMethodsOrder$a = loginMethodsOrder[a]) !== null && _loginMethodsOrder$a !== void 0 ? _loginMethodsOrder$a : maxOrder;
      const bOrder = (_loginMethodsOrder$b = loginMethodsOrder[b]) !== null && _loginMethodsOrder$b !== void 0 ? _loginMethodsOrder$b : maxOrder;
      const {
        mainOption: aMainOption
      } = socialLoginsConfig.loginMethods[a] || {};
      const {
        mainOption: bMainOption
      } = socialLoginsConfig.loginMethods[b] || {};

      // if both are main options, sort by order
      if (aMainOption && bMainOption) {
        return aOrder - bOrder;
      }

      // if one is main option, it should be first
      if (aMainOption) return -1;
      if (bMainOption) return 1;

      // if none are main options, sort by order
      return aOrder - bOrder;
    });
    loginOptions.forEach((method, index) => {
      var _socialLoginsConfig$u;
      const connectorConfig = socialLoginsConfig.loginMethods[method];
      const name = capitalizeFirstLetter(connectorConfig.name || method);
      const order = index + 1;
      const isPrimaryBtn = (socialLoginsConfig === null || socialLoginsConfig === void 0 || (_socialLoginsConfig$u = socialLoginsConfig.uiConfig) === null || _socialLoginsConfig$u === void 0 ? void 0 : _socialLoginsConfig$u.primaryButton) === "socialLogin" && order === 1;
      const loginOptionLength = loginOptions.length;
      const moreThanFour = loginOptionLength >= 4;
      const lengthCheck = moreThanFour ? order > 0 && order <= loginOptionLength : order > 0 && order < 4;
      if (lengthCheck) {
        visibleRows.push({
          method,
          isDark,
          isPrimaryBtn,
          name,
          connector: socialLoginsConfig.connector,
          loginParams: {
            authConnection: connectorConfig.authConnection || method,
            authConnectionId: connectorConfig.authConnectionId,
            groupedAuthConnectionId: connectorConfig.groupedAuthConnectionId,
            extraLoginOptions: connectorConfig.extraLoginOptions,
            name,
            login_hint: ""
          },
          order
        });
      }
      otherRows.push({
        method,
        isDark,
        isPrimaryBtn,
        name: name === "Twitter" ? "X" : name,
        connector: socialLoginsConfig.connector,
        loginParams: {
          authConnection: method,
          authConnectionId: connectorConfig.authConnectionId,
          groupedAuthConnectionId: connectorConfig.groupedAuthConnectionId,
          extraLoginOptions: connectorConfig.extraLoginOptions,
          name,
          login_hint: ""
        },
        order
      });
    });
    setVisibleRow(visibleRows);
    setOtherRow(otherRows);
    setCanShowMore(maxOptions.length > 4); // Update the state based on the condition
  }, [socialLoginsConfig, isDark, buttonRadius]);
  const handleCustomLogin = async (authConnection, loginHint) => {
    try {
      const handler = createPasswordlessHandler(authConnection, {
        loginHint,
        web3authClientId,
        network: web3authNetwork,
        uiConfig: socialLoginsConfig.uiConfig,
        authConnection,
        authBuildEnv
      });
      let token = undefined;
      if (!isTestAccountPattern(authConnection, loginHint)) {
        var _captchaRef$current;
        const res = await ((_captchaRef$current = captchaRef.current) === null || _captchaRef$current === void 0 ? void 0 : _captchaRef$current.execute({
          async: true
        }));
        if (!res) {
          throw WalletLoginError.connectionError("Captcha token is required");
        }
        token = res.response;
      }
      const result = await handler.sendVerificationCode({
        captchaToken: token
      });
      if (result !== null && result !== void 0 && result.error) {
        setPasswordlessErrorMessage(t(result.error));
        return;
      }
      setAuthConnection(authConnection);
      setShowOtpFlow(true);
      setPasswordlessHandler(handler);
    } catch (error) {
      log.error(error);
    } finally {
      setIsPasswordLessLoading(false);
    }
  };
  const handleFormSubmit = async loginHint => {
    setIsPasswordLessLoading(true);
    if (isEmailPasswordLessLoginVisible) {
      const isEmailValid = loginHint.match(/^([\w.%+-]+)@([\w-]+\.)+([\w]{2,})$/i);
      if (isEmailValid) {
        const connectorConfig = socialLoginsConfig.loginMethods[AUTH_CONNECTION.EMAIL_PASSWORDLESS];
        if (connectorConfig.isDefault) {
          return handleSocialLoginClick({
            connector: socialLoginsConfig.connector,
            loginParams: {
              authConnection: AUTH_CONNECTION.EMAIL_PASSWORDLESS,
              authConnectionId: connectorConfig.authConnectionId,
              groupedAuthConnectionId: connectorConfig.groupedAuthConnectionId,
              extraLoginOptions: connectorConfig.extraLoginOptions,
              loginHint: loginHint,
              name: "Email"
            }
          });
        } else {
          return handleCustomLogin(AUTH_CONNECTION.EMAIL_PASSWORDLESS, loginHint);
        }
      }
    }
    if (isSmsPasswordLessLoginVisible) {
      const number = loginHint.startsWith("+") ? loginHint : `${countryCode}${loginHint}`;
      const result = await validatePhoneNumber(number);
      if (result.success) {
        const finalLoginHint = typeof result.parsed_number === "string" ? result.parsed_number : number;
        const connectorConfig = socialLoginsConfig.loginMethods[AUTH_CONNECTION.SMS_PASSWORDLESS];
        if (connectorConfig.isDefault) {
          return handleSocialLoginClick({
            connector: socialLoginsConfig.connector,
            loginParams: {
              authConnection: AUTH_CONNECTION.SMS_PASSWORDLESS,
              authConnectionId: connectorConfig.authConnectionId,
              groupedAuthConnectionId: connectorConfig.groupedAuthConnectionId,
              extraLoginOptions: connectorConfig.extraLoginOptions,
              loginHint: finalLoginHint,
              name: "Mobile"
            }
          });
        } else {
          setCountryFlag(result.country_flag);
          return handleCustomLogin(AUTH_CONNECTION.SMS_PASSWORDLESS, finalLoginHint);
        }
      }
    }
    setPasswordlessErrorMessage(invalidInputErrorMessage);
    setIsPasswordLessLoading(false);
    return undefined;
  };
  const title = useMemo(() => {
    if (isEmailPasswordLessLoginVisible && isSmsPasswordLessLoginVisible) return t("modal.social.passwordless-title");
    if (isEmailPasswordLessLoginVisible) return t("modal.social.email");
    return t("modal.social.phone");
  }, [isEmailPasswordLessLoginVisible, isSmsPasswordLessLoginVisible, t]);
  const placeholder = useMemo(() => {
    if (isEmailPasswordLessLoginVisible && isSmsPasswordLessLoginVisible) return "+(00)123456/name@example.com";
    if (isEmailPasswordLessLoginVisible) return "name@example.com";
    return "+(00)123456";
  }, [isEmailPasswordLessLoginVisible, isSmsPasswordLessLoginVisible]);
  const invalidInputErrorMessage = useMemo(() => {
    if (isEmailPasswordLessLoginVisible && isSmsPasswordLessLoginVisible) return t("modal.errors-invalid-number-email");
    if (isEmailPasswordLessLoginVisible) return t("modal.errors-invalid-email");
    return t("modal.errors-invalid-number");
  }, [isEmailPasswordLessLoginVisible, isSmsPasswordLessLoginVisible, t]);
  useEffect(() => {
    const getLocation = async () => {
      const result = await getUserCountry();
      if (result && result.dialCode) {
        setCountryCode(result.dialCode);
      }
    };
    if (isSmsPasswordLessLoginVisible) getLocation();
  }, [isSmsPasswordLessLoginVisible]);
  const handleOtpComplete = async otp => {
    setOtpLoading(true);
    if (otpErrorMessage) setOtpErrorMessage("");
    try {
      var _result$data;
      const connectorConfig = socialLoginsConfig.loginMethods[authConnection];
      const result = await (passwordlessHandler === null || passwordlessHandler === void 0 ? void 0 : passwordlessHandler.verifyCode(otp));
      if (result !== null && result !== void 0 && result.error) {
        setOtpErrorMessage(t(result.error));
        return;
      }
      if (result !== null && result !== void 0 && (_result$data = result.data) !== null && _result$data !== void 0 && _result$data.id_token) {
        var _result$data2;
        return handleSocialLoginClick({
          connector: socialLoginsConfig.connector,
          loginParams: {
            authConnection: authConnection,
            authConnectionId: connectorConfig.authConnectionId,
            groupedAuthConnectionId: connectorConfig.groupedAuthConnectionId,
            extraLoginOptions: _objectSpread(_objectSpread({}, connectorConfig.extraLoginOptions), {}, {
              id_token: (_result$data2 = result.data) === null || _result$data2 === void 0 ? void 0 : _result$data2.id_token
            }),
            loginHint: passwordlessHandler.passwordlessParams.loginHint,
            name: passwordlessHandler.name
          }
        });
      }
    } catch (error) {
      log.error(error);
    } finally {
      setOtpLoading(false);
    }
  };

  /**
   * Installed wallet click logic:
   * - For MetaMask: If not injected and on desktop, display QR code for connection.
   * - If wallet supports multiple chain namespaces, prompt user to select a chain.
   * - Otherwise, connect directly using the wallet connector.
   */
  const handleInstalledWalletClick = wallet => {
    var _wallet$chainNamespac;
    analytics === null || analytics === void 0 || analytics.track(ANALYTICS_EVENTS.EXTERNAL_WALLET_SELECTED, {
      connector: wallet.name,
      wallet_name: wallet.displayName,
      is_installed: wallet.isInstalled,
      is_injected: wallet.hasInjectedWallet,
      chain_namespaces: wallet.chainNamespaces,
      has_wallet_connect: wallet.hasWalletConnect,
      has_install_links: wallet.hasInstallLinks,
      has_wallet_registry_item: !!wallet.walletRegistryItem,
      total_external_wallets: totalExternalWallets
    });
    log.info("handleInstalledWalletClick", wallet);
    // for non-injected Metamask on desktop, show QR code to connect
    if (wallet.name === WALLET_CONNECTORS.METAMASK && !wallet.hasInjectedWallet && deviceDetails.platform === "desktop") {
      handleExternalWalletClick({
        connector: wallet.name
      });
      // We should show QR code only if the wallet is not installed.
      setBodyState(_objectSpread(_objectSpread({}, bodyState), {}, {
        metamaskQrCode: {
          show: true,
          wallet: wallet
        }
      }));
      return;
    }

    // when having multiple namespaces, ask user to select one
    if (((_wallet$chainNamespac = wallet.chainNamespaces) === null || _wallet$chainNamespac === void 0 ? void 0 : _wallet$chainNamespac.length) > 1) {
      setBodyState(_objectSpread(_objectSpread({}, bodyState), {}, {
        multiChainSelector: {
          show: true,
          wallet: wallet
        }
      }));
    } else {
      handleExternalWalletClick({
        connector: wallet.name
      });
    }
  };
  const installedExternalWallets = useMemo(() => {
    if (showInstalledExternalWallets) return installedExternalWalletConfig;
    // always show MetaMask
    return installedExternalWalletConfig.filter(wallet => wallet.name === WALLET_CONNECTORS.METAMASK);
  }, [installedExternalWalletConfig, showInstalledExternalWallets]);
  const handleConnectWallet = useCallback(e => {
    analytics === null || analytics === void 0 || analytics.track(ANALYTICS_EVENTS.EXTERNAL_WALLET_LIST_EXPANDED, {
      total_external_wallets: totalExternalWallets,
      installed_external_wallets: installedExternalWallets.length
    });
    setIsPasswordLessCtaClicked(false);
    e === null || e === void 0 || e.preventDefault();
    if (handleExternalWalletBtnClick) handleExternalWalletBtnClick(true);
  }, [analytics, handleExternalWalletBtnClick, installedExternalWallets.length, totalExternalWallets]);
  useEffect(() => {
    if (showExternalWalletButton && !areSocialLoginsVisible && !showPasswordLessInput) {
      handleConnectWallet();
    }
  }, [showExternalWalletButton, areSocialLoginsVisible, showPasswordLessInput, handleConnectWallet]);
  if (showOtpFlow) {
    return /*#__PURE__*/jsx(LoginOtp, {
      otpLoading: otpLoading,
      loginHint: passwordlessHandler === null || passwordlessHandler === void 0 ? void 0 : passwordlessHandler.passwordlessParams.loginHint,
      setShowOtpFlow: setShowOtpFlow,
      authConnection: authConnection,
      handleOtpComplete: handleOtpComplete,
      errorMessage: otpErrorMessage,
      countryFlag: countryFlag
    });
  }
  const socialLoginSection = (otherRow = []) => {
    return /*#__PURE__*/jsx(SocialLoginList, {
      otherRow: otherRow,
      isDark: isDark,
      visibleRow: visibleRow,
      canShowMore: canShowMore,
      handleSocialLoginClick: handleSocialLoginClick,
      socialLoginsConfig: socialLoginsConfig,
      handleExpandSocialLogins: handleSocialLoginExpand,
      buttonRadius: buttonRadius
    }, "social-login-section");
  };
  const passwordlessLoginSection = () => {
    return /*#__PURE__*/jsx(LoginPasswordLess, {
      isModalVisible: isModalVisible,
      isPasswordLessCtaClicked: isPasswordLessCtaClicked,
      setIsPasswordLessCtaClicked: setIsPasswordLessCtaClicked,
      title: title,
      placeholder: placeholder,
      handleFormSubmit: handleFormSubmit,
      errorMessage: passwordlessErrorMessage,
      isDark: isDark,
      buttonRadius: buttonRadius,
      isPasswordLessLoading: isPasswordLessLoading
    }, "passwordless-section");
  };
  const externalWalletSection = () => {
    return /*#__PURE__*/jsxs("div", {
      className: cn("w3a--flex w3a--w-full w3a--flex-col w3a--items-start w3a--justify-start w3a--gap-y-2"),
      children: [installedExternalWallets.length > 0 && installedExternalWallets.map(wallet => /*#__PURE__*/jsxs("button", {
        type: "button",
        className: cn("w3a--btn !w3a--justify-between w3a--group w3a--relative w3a--overflow-hidden", {
          "w3a--rounded-full": buttonRadius === "pill",
          "w3a--rounded-lg": buttonRadius === "rounded",
          "w3a--rounded-none": buttonRadius === "square"
        }),
        onClick: () => handleInstalledWalletClick(wallet),
        children: [/*#__PURE__*/jsx("p", {
          className: "w3a--max-w-[180px] w3a--truncate w3a--text-base w3a--font-normal w3a--text-app-gray-700 dark:w3a--text-app-white",
          children: wallet.displayName
        }), /*#__PURE__*/jsxs("div", {
          className: "w3a--absolute w3a--right-4 w3a--top-1/2 w3a--flex w3a--w-auto -w3a--translate-y-1/2 w3a--items-center w3a--gap-x-2 w3a--transition-all w3a--duration-300 group-hover:w3a--translate-x-6 group-hover:w3a--opacity-0",
          children: [wallet.hasInjectedWallet && /*#__PURE__*/jsx("span", {
            className: "w3a--inline-flex w3a--items-center w3a--rounded-md w3a--bg-app-primary-100 w3a--px-2 w3a--py-1 w3a--text-xs w3a--font-medium w3a--text-app-primary-800  dark:w3a--border dark:w3a--border-app-primary-400 dark:w3a--bg-transparent dark:w3a--text-app-primary-400",
            children: t("modal.external.installed")
          }), /*#__PURE__*/jsx("figure", {
            className: "w3a--size-5",
            children: /*#__PURE__*/jsx(Image, {
              imageData: wallet.icon,
              imageId: `login-${wallet.name}`,
              hoverImageId: `login-${wallet.name}`,
              fallbackImageId: "wallet",
              height: "24",
              width: "24",
              isButton: true,
              extension: wallet.imgExtension || "webp"
            })
          })]
        }), /*#__PURE__*/jsx("img", {
          id: "injected-wallet-arrow",
          className: "w3a--absolute w3a--right-4 w3a--top-1/2 -w3a--translate-x-10 -w3a--translate-y-1/2 w3a--opacity-0 w3a--transition-all w3a--duration-300 group-hover:w3a--translate-x-0 group-hover:w3a--opacity-100",
          src: getIcons(isDark ? "chevron-right-dark" : "chevron-right-light"),
          alt: "arrow"
        })]
      }, wallet.name)), totalExternalWallets > 3 && /*#__PURE__*/jsxs("button", {
        type: "button",
        className: cn("w3a--btn !w3a--justify-between w3a--group w3a--relative w3a--overflow-hidden", {
          "w3a--rounded-full": buttonRadius === "pill",
          "w3a--rounded-lg": buttonRadius === "rounded",
          "w3a--rounded-none": buttonRadius === "square"
        }),
        onClick: handleConnectWallet,
        children: [/*#__PURE__*/jsx("p", {
          className: "w3a--text-base w3a--font-normal w3a--text-app-gray-900 dark:w3a--text-app-white",
          children: t("modal.external.all-wallets")
        }), showExternalWalletCount && totalExternalWallets > 0 && /*#__PURE__*/jsx("div", {
          id: "external-wallet-count",
          className: "w3a--absolute w3a--right-4 w3a--top-1/2 w3a--w-auto -w3a--translate-y-1/2 w3a--rounded-full w3a--bg-app-primary-100 w3a--px-2.5 w3a--py-0.5 w3a--text-xs w3a--font-medium w3a--text-app-primary-800 w3a--transition-all w3a--delay-300 w3a--duration-300 group-hover:w3a--translate-x-6 group-hover:w3a--opacity-0 group-hover:w3a--delay-0 dark:w3a--border dark:w3a--border-app-primary-500 dark:w3a--bg-transparent dark:w3a--text-app-primary-500",
          children: totalExternalWallets - 1
        }), /*#__PURE__*/jsx("img", {
          id: "external-wallet-arrow",
          className: "w3a--absolute w3a--right-4 w3a--top-1/2 -w3a--translate-x-10 -w3a--translate-y-1/2 w3a--opacity-0 w3a--transition-all w3a--duration-300 group-hover:w3a--translate-x-0 group-hover:w3a--opacity-100",
          src: getIcons(isDark ? "chevron-right-dark" : "chevron-right-light"),
          alt: "arrow"
        })]
      })]
    }, "external-wallets-section");
  };
  const headerLogo = [DEFAULT_LOGO_DARK, DEFAULT_LOGO_LIGHT].includes(appLogo) ? "" : appLogo;
  const delimiter = index => {
    return /*#__PURE__*/jsxs("div", {
      className: cn("w3a--flex w3a--w-full w3a--items-center w3a--gap-x-2", headerLogo ? "w3a--my-2" : "w3a--my-4"),
      children: [/*#__PURE__*/jsx("div", {
        className: "w3a--h-px w3a--w-full w3a--bg-app-gray-200 dark:w3a--bg-app-gray-500"
      }), /*#__PURE__*/jsx("p", {
        className: "w3a--text-xs w3a--font-normal w3a--uppercase w3a--text-app-gray-400 dark:w3a--text-app-gray-400",
        children: "or"
      }), /*#__PURE__*/jsx("div", {
        className: "w3a--h-px w3a--w-full w3a--bg-app-gray-200 dark:w3a--bg-app-gray-500"
      })]
    }, `section-delimiter-${index}`);
  };
  const defaultView = () => {
    var _socialLoginsConfig$u2;
    const sectionMap = {
      social: socialLoginSection,
      passwordless: passwordlessLoginSection,
      externalWallets: externalWalletSection
    };
    const sectionVisibility = {
      social: areSocialLoginsVisible,
      passwordless: showPasswordLessInput,
      externalWallets: showExternalWalletButton
    };
    const signInMethods = ((_socialLoginsConfig$u2 = socialLoginsConfig.uiConfig) === null || _socialLoginsConfig$u2 === void 0 ? void 0 : _socialLoginsConfig$u2.signInMethods) || ["social", "passwordless", "externalWallets"];

    // add missing signInMethods in case uiConfig.signInMethods is not set correctly
    Object.entries(sectionVisibility).forEach(([method, visibility]) => {
      if (visibility && !signInMethods.includes(method)) {
        signInMethods.push(method);
      }
    });
    const sections = signInMethods.map(method => sectionVisibility[method] && sectionMap[method]()).filter(Boolean);

    // add delimiter between external wallets and other sections
    if (sections.length === 3) {
      const externalWalletIndex = signInMethods.findIndex(section => section === "externalWallets");
      if (externalWalletIndex === 0) {
        // add after it
        sections.splice(1, 0, delimiter(1));
      } else if (externalWalletIndex === 1) {
        // add before it
        sections.splice(1, 0, delimiter(1));
        // add after it
        sections.splice(3, 0, delimiter(2));
      } else if (externalWalletIndex === 2) {
        // add before it
        sections.splice(2, 0, delimiter(1));
      }
    } else if (sections.length === 2) {
      if (sectionVisibility["externalWallets"]) {
        sections.splice(1, 0, delimiter(1));
      }
    }
    return sections;
  };
  const socialLoginExpandedView = () => socialLoginSection(otherRow);
  return /*#__PURE__*/jsxs("div", {
    className: "w3a--flex w3a--flex-col w3a--items-center w3a--gap-y-4 w3a--p-2",
    children: [/*#__PURE__*/jsxs("div", {
      className: cn("w3a--flex w3a--flex-col w3a--items-center w3a--justify-center w3a--gap-y-2 w3a--pt-6", logoAlignment === "center" ? "" : "w3a--w-full"),
      children: [headerLogo && /*#__PURE__*/jsx("figure", {
        className: cn("w3a--mx-auto w3a--h-12 w3a--w-[200px]", logoAlignment === "center" ? "w3a--flex w3a--justify-center w3a--items-center" : "w3a--ml-0 w3a--w-auto"),
        children: /*#__PURE__*/jsx("img", {
          src: headerLogo,
          alt: "Logo",
          className: "w3a--size-full w3a--object-contain"
        })
      }), /*#__PURE__*/jsx("p", {
        className: cn("w3a--text-app-gray-900 dark:w3a--text-app-white", logoAlignment === "center" ? "w3a--text-center" : "w3a--text-left w3a--w-full w3a--ml-4", headerLogo ? "w3a--text-lg w3a--font-semibold" : "w3a--text-3xl w3a--font-medium"),
        children: t("modal.social.sign-in")
      })]
    }), /*#__PURE__*/jsx(HCaptcha, {
      ref: captchaRef,
      sitekey: CAPTCHA_SITE_KEY,
      size: "invisible",
      languageOverride: socialLoginsConfig.uiConfig.defaultLanguage,
      theme: socialLoginsConfig.uiConfig.theme,
      onOpen: () => setShowCaptcha(true),
      onClose: () => setShowCaptcha(false),
      onError: () => setCaptchaError("passwordless.captcha-default-error"),
      onChalExpired: () => setCaptchaError("passwordless.captcha-default-error")
    }), captchaError && showCaptcha && /*#__PURE__*/jsx("p", {
      className: "-w3a--mt-2 w3a--w-full w3a--pl-6 w3a--text-start w3a--text-xs w3a--font-normal w3a--text-app-red-500 dark:w3a--text-app-red-400",
      children: t(captchaError)
    }), !showCaptcha && /*#__PURE__*/jsxs("div", {
      className: "w3a--flex w3a--w-full w3a--flex-col w3a--items-center w3a--justify-center w3a--gap-y-2",
      children: [!expandSocialLogins && defaultView(), expandSocialLogins && socialLoginExpandedView()]
    })]
  });
}

export { Login as default };
