"use client";
import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
import styled from "@emotion/styled";
import { useState } from "react";
import { useCustomTheme } from "../../../core/design-system/CustomThemeProvider.js";
import { fontSize, iconSize, spacing, } from "../../../core/design-system/index.js";
import { useConnectUI } from "../../../core/hooks/others/useWalletConnectionCtx.js";
import { useSetSelectionData } from "../../providers/wallet-ui-states-provider.js";
import { TOS } from "../../ui/ConnectWallet/Modal/TOS.js";
import { useScreenContext } from "../../ui/ConnectWallet/Modal/screen.js";
import { PoweredByThirdweb } from "../../ui/ConnectWallet/PoweredByTW.js";
import { WalletTypeRowButton } from "../../ui/ConnectWallet/WalletTypeRowButton.js";
import { emailIcon, passkeyIcon, phoneIcon, } from "../../ui/ConnectWallet/icons/dataUris.js";
import { Img } from "../../ui/components/Img.js";
import { Spacer } from "../../ui/components/Spacer.js";
import { TextDivider } from "../../ui/components/TextDivider.js";
import { Container, ModalHeader } from "../../ui/components/basic.js";
import { Button } from "../../ui/components/buttons.js";
import { InputSelectionUI } from "./InputSelectionUI.js";
import { openOauthSignInWindow } from "./openOauthSignInWindow.js";
import { socialIcons } from "./socialIcons.js";
import { setLastAuthProvider } from "./storage.js";
import { validateEmail } from "./validateEmail.js";
const defaultAuthOptions = [
    "email",
    "phone",
    "google",
    "apple",
    "facebook",
    "passkey",
];
/**
 * @internal
 */
export const InAppWalletFormUI = (props) => {
    const locale = props.locale;
    const { chain, client, connectModal } = useConnectUI();
    const { wallet } = props;
    const setData = useSetSelectionData();
    const themeObj = 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] = 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 = 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 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 (_jsxs(Container, { flex: "column", gap: "md", style: {
            position: "relative",
        }, children: [config?.metadata?.image && (_jsx(Container, { flex: "row", center: "both", children: _jsx(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 && (_jsx(Container, { flex: showOnlyIcons ? "row" : "column", center: "x", gap: "sm", style: {
                    justifyContent: "space-between",
                }, children: socialLogins.map((loginMethod) => {
                    const imgIconSize = showOnlyIcons ? iconSize.lg : iconSize.md;
                    return (_jsxs(SocialButton, { "aria-label": `Login with ${loginMethod}`, "data-variant": showOnlyIcons ? "icon" : "full", variant: "outline", fullWidth: !showOnlyIcons, onClick: () => {
                            handleSocialLogin(loginMethod);
                        }, children: [_jsx(Img, { src: socialIcons[loginMethod], width: imgIconSize, height: imgIconSize, client: client }), !showOnlyIcons && loginMethodsLabel[loginMethod]] }, loginMethod));
                }) })), connectModal.size === "wide" &&
                hasSocialLogins &&
                (isEmailEnabled || isPhoneEnabled) && _jsx(TextDivider, { text: locale.or }), isEmailEnabled && (_jsx(_Fragment, { children: inputMode === "email" ? (_jsx(InputSelectionUI, { type: type, onSelect: (value) => {
                        setData({ emailLogin: value });
                        props.select();
                    }, placeholder: placeholder, name: "email", errorMessage: (input) => {
                        const isValidEmail = validateEmail(input.toLowerCase());
                        if (!isValidEmail) {
                            return locale.invalidEmail;
                        }
                        return undefined;
                    }, emptyErrorMessage: emptyErrorMessage, submitButtonText: locale.submitEmail })) : (_jsx(WalletTypeRowButton, { client: client, icon: emailIcon, onClick: () => {
                        setInputMode("email");
                    }, 
                    // TODO locale
                    title: "Email address" })) })), isPhoneEnabled && (_jsx(_Fragment, { children: inputMode === "phone" ? (_jsx(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 })) : (_jsx(WalletTypeRowButton, { client: client, icon: phoneIcon, onClick: () => {
                        setInputMode("phone");
                    }, 
                    // TODO locale
                    title: "Phone number" })) })), passKeyEnabled && (_jsx(_Fragment, { children: _jsx(WalletTypeRowButton, { client: client, icon: passkeyIcon, onClick: () => {
                        handlePassKeyLogin();
                    }, 
                    // TODO locale
                    title: "Passkey" }) }))] }));
};
/**
 * @internal
 */
export function InAppWalletFormUIScreen(props) {
    const locale = props.locale.emailLoginScreen;
    const { connectModal } = useConnectUI();
    const isCompact = connectModal.size === "compact";
    const { initialScreen, screen } = useScreenContext();
    const onBack = screen === props.wallet && initialScreen === props.wallet
        ? undefined
        : props.goBack;
    return (_jsxs(Container, { fullHeight: true, flex: "column", p: "lg", animate: "fadein", style: {
            minHeight: "250px",
        }, children: [isCompact ? (_jsxs(_Fragment, { children: [_jsx(ModalHeader, { onBack: onBack, title: locale.title }), _jsx(Spacer, { y: "sm" })] })) : null, _jsx(Container, { expand: true, flex: "column", center: "y", p: isCompact ? undefined : "lg", children: _jsx(InAppWalletFormUI, { ...props }) }), isCompact &&
                (connectModal.showThirdwebBranding !== false ||
                    connectModal.termsOfServiceUrl ||
                    connectModal.privacyPolicyUrl) && _jsx(Spacer, { y: "xl" }), _jsxs(Container, { flex: "column", gap: "lg", children: [_jsx(TOS, { termsOfServiceUrl: connectModal.termsOfServiceUrl, privacyPolicyUrl: connectModal.privacyPolicyUrl }), connectModal.showThirdwebBranding !== false && _jsx(PoweredByThirdweb, {})] })] }));
}
const SocialButton = /* @__PURE__ */ styled(Button)({
    "&[data-variant='full']": {
        display: "flex",
        justifyContent: "flex-start",
        padding: spacing.md,
        gap: spacing.md,
        fontSize: fontSize.md,
        fontWeight: 500,
        transition: "background-color 0.2s ease",
        "&:active": {
            boxShadow: "none",
        },
    },
    "&[data-variant='icon']": {
        padding: spacing.sm,
        flexGrow: 1,
    },
});
//# sourceMappingURL=InAppWalletFormUI.js.map