"use strict";
"use client";
Object.defineProperty(exports, "__esModule", { value: true });
exports.InAppWalletFormUIScreen = exports.InAppWalletFormUI = void 0;
const jsx_runtime_1 = require("react/jsx-runtime");
const styled_1 = require("@emotion/styled");
const react_1 = require("react");
const CustomThemeProvider_js_1 = require("../../../core/design-system/CustomThemeProvider.js");
const index_js_1 = require("../../../core/design-system/index.js");
const useWalletConnectionCtx_js_1 = require("../../../core/hooks/others/useWalletConnectionCtx.js");
const wallet_ui_states_provider_js_1 = require("../../providers/wallet-ui-states-provider.js");
const TOS_js_1 = require("../../ui/ConnectWallet/Modal/TOS.js");
const screen_js_1 = require("../../ui/ConnectWallet/Modal/screen.js");
const PoweredByTW_js_1 = require("../../ui/ConnectWallet/PoweredByTW.js");
const WalletTypeRowButton_js_1 = require("../../ui/ConnectWallet/WalletTypeRowButton.js");
const dataUris_js_1 = require("../../ui/ConnectWallet/icons/dataUris.js");
const Img_js_1 = require("../../ui/components/Img.js");
const Spacer_js_1 = require("../../ui/components/Spacer.js");
const TextDivider_js_1 = require("../../ui/components/TextDivider.js");
const basic_js_1 = require("../../ui/components/basic.js");
const buttons_js_1 = require("../../ui/components/buttons.js");
const InputSelectionUI_js_1 = require("./InputSelectionUI.js");
const openOauthSignInWindow_js_1 = require("./openOauthSignInWindow.js");
const socialIcons_js_1 = require("./socialIcons.js");
const storage_js_1 = require("./storage.js");
const validateEmail_js_1 = require("./validateEmail.js");
const defaultAuthOptions = [
    "email",
    "phone",
    "google",
    "apple",
    "facebook",
    "passkey",
];
/**
 * @internal
 */
const InAppWalletFormUI = (props) => {
    const locale = props.locale;
    const { chain, client, connectModal } = (0, useWalletConnectionCtx_js_1.useConnectUI)();
    const { wallet } = props;
    const setData = (0, wallet_ui_states_provider_js_1.useSetSelectionData)();
    const themeObj = (0, CustomThemeProvider_js_1.useCustomTheme)();
    const loginMethodsLabel = {
        google: locale.signInWithGoogle,
        facebook: locale.signInWithFacebook,
        apple: locale.signInWithApple,
    };
    const config = props.wallet.getConfig();
    const authOptions = config?.auth?.options || defaultAuthOptions;
    const passKeyEnabled = authOptions.includes("passkey");
    const emailIndex = authOptions.indexOf("email");
    const isEmailEnabled = emailIndex !== -1;
    const phoneIndex = authOptions.indexOf("phone");
    const isPhoneEnabled = phoneIndex !== -1;
    const [inputMode, setInputMode] = (0, react_1.useState)(() => {
        if (isEmailEnabled && isPhoneEnabled) {
            return emailIndex < phoneIndex ? "email" : "phone";
        }
        if (isEmailEnabled) {
            return "email";
        }
        if (isPhoneEnabled) {
            return "phone";
        }
        return "none";
    });
    const placeholder = inputMode === "email" ? locale.emailPlaceholder : locale.phonePlaceholder;
    const emptyErrorMessage = inputMode === "email" ? locale.emailRequired : locale.phoneRequired;
    let type = "text";
    if (inputMode === "email") {
        type = "email";
    }
    else if (inputMode === "phone") {
        type = "tel";
    }
    const socialLogins = authOptions.filter((x) => x === "google" || x === "apple" || x === "facebook");
    const hasSocialLogins = socialLogins.length > 0;
    // Need to trigger login on button click to avoid popup from being blocked
    const handleSocialLogin = async (strategy) => {
        try {
            const socialLoginWindow = (0, openOauthSignInWindow_js_1.openOauthSignInWindow)(strategy, themeObj);
            if (!socialLoginWindow) {
                throw new Error("Failed to open login window");
            }
            const connectPromise = wallet.connect({
                chain,
                client,
                strategy: strategy,
                openedWindow: socialLoginWindow,
                closeOpenedWindow: (openedWindow) => {
                    openedWindow.close();
                },
            });
            await (0, storage_js_1.setLastAuthProvider)(strategy);
            setData({
                socialLogin: {
                    type: strategy,
                    connectionPromise: connectPromise,
                },
            });
            props.select(); // show Connect UI
            // Note: do not call done() here, it will be called InAppWalletSocialLogin component
            // we simply trigger the connect and save promise here - its resolution is handled in InAppWalletSocialLogin
        }
        catch (e) {
            console.error(`Error sign in with ${strategy}`, e);
        }
    };
    function handlePassKeyLogin() {
        setData({
            passkeyLogin: true,
        });
        props.select();
    }
    const showOnlyIcons = socialLogins.length > 1;
    if (config?.metadata?.image &&
        (!config.metadata.image.height || !config.metadata.image.width)) {
        console.warn("Image is not properly configured. Please set height and width.", config.metadata.image);
    }
    return ((0, jsx_runtime_1.jsxs)(basic_js_1.Container, { flex: "column", gap: "md", style: {
            position: "relative",
        }, children: [config?.metadata?.image && ((0, jsx_runtime_1.jsx)(basic_js_1.Container, { flex: "row", center: "both", children: (0, jsx_runtime_1.jsx)(Img_js_1.Img, { loading: "eager", client: client, style: {
                        maxHeight: "100px",
                        maxWidth: "300px",
                    }, src: config.metadata.image.src, alt: config.metadata.image.alt, width: Math.min(config.metadata.image.width ?? 300, 300)?.toString(), height: Math.min(config.metadata.image.height ?? 100, 100)?.toString() }) })), hasSocialLogins && ((0, jsx_runtime_1.jsx)(basic_js_1.Container, { flex: showOnlyIcons ? "row" : "column", center: "x", gap: "sm", style: {
                    justifyContent: "space-between",
                }, children: socialLogins.map((loginMethod) => {
                    const imgIconSize = showOnlyIcons ? index_js_1.iconSize.lg : index_js_1.iconSize.md;
                    return ((0, jsx_runtime_1.jsxs)(SocialButton, { "aria-label": `Login with ${loginMethod}`, "data-variant": showOnlyIcons ? "icon" : "full", variant: "outline", fullWidth: !showOnlyIcons, onClick: () => {
                            handleSocialLogin(loginMethod);
                        }, children: [(0, jsx_runtime_1.jsx)(Img_js_1.Img, { src: socialIcons_js_1.socialIcons[loginMethod], width: imgIconSize, height: imgIconSize, client: client }), !showOnlyIcons && loginMethodsLabel[loginMethod]] }, loginMethod));
                }) })), connectModal.size === "wide" &&
                hasSocialLogins &&
                (isEmailEnabled || isPhoneEnabled) && (0, jsx_runtime_1.jsx)(TextDivider_js_1.TextDivider, { text: locale.or }), isEmailEnabled && ((0, jsx_runtime_1.jsx)(jsx_runtime_1.Fragment, { children: inputMode === "email" ? ((0, jsx_runtime_1.jsx)(InputSelectionUI_js_1.InputSelectionUI, { type: type, onSelect: (value) => {
                        setData({ emailLogin: value });
                        props.select();
                    }, placeholder: placeholder, name: "email", errorMessage: (input) => {
                        const isValidEmail = (0, validateEmail_js_1.validateEmail)(input.toLowerCase());
                        if (!isValidEmail) {
                            return locale.invalidEmail;
                        }
                        return undefined;
                    }, emptyErrorMessage: emptyErrorMessage, submitButtonText: locale.submitEmail })) : ((0, jsx_runtime_1.jsx)(WalletTypeRowButton_js_1.WalletTypeRowButton, { client: client, icon: dataUris_js_1.emailIcon, onClick: () => {
                        setInputMode("email");
                    }, 
                    // TODO locale
                    title: "Email address" })) })), isPhoneEnabled && ((0, jsx_runtime_1.jsx)(jsx_runtime_1.Fragment, { children: inputMode === "phone" ? ((0, jsx_runtime_1.jsx)(InputSelectionUI_js_1.InputSelectionUI, { format: "phone", type: type, onSelect: (value) => {
                        // removes white spaces and special characters
                        setData({ phoneLogin: value.replace(/[-\(\) ]/g, "") });
                        props.select();
                    }, placeholder: placeholder, name: "phone", errorMessage: (_input) => {
                        // removes white spaces and special characters
                        const input = _input.replace(/[-\(\) ]/g, "");
                        const isPhone = /^[0-9]+$/.test(input);
                        if (!isPhone && isPhoneEnabled) {
                            return locale.invalidPhone;
                        }
                        return undefined;
                    }, emptyErrorMessage: emptyErrorMessage, submitButtonText: locale.submitEmail })) : ((0, jsx_runtime_1.jsx)(WalletTypeRowButton_js_1.WalletTypeRowButton, { client: client, icon: dataUris_js_1.phoneIcon, onClick: () => {
                        setInputMode("phone");
                    }, 
                    // TODO locale
                    title: "Phone number" })) })), passKeyEnabled && ((0, jsx_runtime_1.jsx)(jsx_runtime_1.Fragment, { children: (0, jsx_runtime_1.jsx)(WalletTypeRowButton_js_1.WalletTypeRowButton, { client: client, icon: dataUris_js_1.passkeyIcon, onClick: () => {
                        handlePassKeyLogin();
                    }, 
                    // TODO locale
                    title: "Passkey" }) }))] }));
};
exports.InAppWalletFormUI = InAppWalletFormUI;
/**
 * @internal
 */
function InAppWalletFormUIScreen(props) {
    const locale = props.locale.emailLoginScreen;
    const { connectModal } = (0, useWalletConnectionCtx_js_1.useConnectUI)();
    const isCompact = connectModal.size === "compact";
    const { initialScreen, screen } = (0, screen_js_1.useScreenContext)();
    const onBack = screen === props.wallet && initialScreen === props.wallet
        ? undefined
        : props.goBack;
    return ((0, jsx_runtime_1.jsxs)(basic_js_1.Container, { fullHeight: true, flex: "column", p: "lg", animate: "fadein", style: {
            minHeight: "250px",
        }, children: [isCompact ? ((0, jsx_runtime_1.jsxs)(jsx_runtime_1.Fragment, { children: [(0, jsx_runtime_1.jsx)(basic_js_1.ModalHeader, { onBack: onBack, title: locale.title }), (0, jsx_runtime_1.jsx)(Spacer_js_1.Spacer, { y: "sm" })] })) : null, (0, jsx_runtime_1.jsx)(basic_js_1.Container, { expand: true, flex: "column", center: "y", p: isCompact ? undefined : "lg", children: (0, jsx_runtime_1.jsx)(exports.InAppWalletFormUI, { ...props }) }), isCompact &&
                (connectModal.showThirdwebBranding !== false ||
                    connectModal.termsOfServiceUrl ||
                    connectModal.privacyPolicyUrl) && (0, jsx_runtime_1.jsx)(Spacer_js_1.Spacer, { y: "xl" }), (0, jsx_runtime_1.jsxs)(basic_js_1.Container, { flex: "column", gap: "lg", children: [(0, jsx_runtime_1.jsx)(TOS_js_1.TOS, { termsOfServiceUrl: connectModal.termsOfServiceUrl, privacyPolicyUrl: connectModal.privacyPolicyUrl }), connectModal.showThirdwebBranding !== false && (0, jsx_runtime_1.jsx)(PoweredByTW_js_1.PoweredByThirdweb, {})] })] }));
}
exports.InAppWalletFormUIScreen = InAppWalletFormUIScreen;
const SocialButton = /* @__PURE__ */ (0, styled_1.default)(buttons_js_1.Button)({
    "&[data-variant='full']": {
        display: "flex",
        justifyContent: "flex-start",
        padding: index_js_1.spacing.md,
        gap: index_js_1.spacing.md,
        fontSize: index_js_1.fontSize.md,
        fontWeight: 500,
        transition: "background-color 0.2s ease",
        "&:active": {
            boxShadow: "none",
        },
    },
    "&[data-variant='icon']": {
        padding: index_js_1.spacing.sm,
        flexGrow: 1,
    },
});
//# sourceMappingURL=InAppWalletFormUI.js.map