var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
// eslint-disable-next-line import/no-unresolved
import { parseInput } from "@leekone/bnsjs/utils/validation";
import { LOGIN_PROVIDER } from "@toruslabs/openlogin-utils";
import { useContext, useEffect, useMemo, useState } from "react";
import { useTranslation } from "react-i18next";
import { ThemedContext } from "../context/ThemeContext";
import { getUserCountry, validatePhoneNumber } from "../utils";
import { BNSContext } from "./BNSProvider";
import Icon from "./Icon";
export default function SocialLoginPasswordless(props) {
    const { handleSocialLoginClick, adapter, web3AuthNetwork, isPrimaryBtn, isEmailVisible, isSmsVisible } = props;
    const { isDark } = useContext(ThemedContext);
    const [fieldValue, setFieldValue] = useState("");
    const [countryCode, setCountryCode] = useState("");
    const [isValidInput, setIsValidInput] = useState(null);
    const [biValue, setBiuValue] = useState("");
    const [biuValid, setBiuValid] = useState(false);
    const bns = BNSContext();
    const [t] = useTranslation();
    const handleFormSubmit = (e) => __awaiter(this, void 0, void 0, function* () {
        e.preventDefault();
        const value = fieldValue;
        const isEmailValid = value.match(/^([\w.%+-]+)@([\w-]+\.)+([\w]{2,})$/i);
        if (isEmailValid) {
            return handleSocialLoginClick({ adapter, loginParams: { loginProvider: LOGIN_PROVIDER.EMAIL_PASSWORDLESS, login_hint: value, name: "Email" } });
        }
        const number = value.startsWith("+") ? value : `${countryCode}${value}`;
        const result = yield validatePhoneNumber(number, web3AuthNetwork);
        if (result) {
            return handleSocialLoginClick({
                adapter,
                loginParams: { loginProvider: LOGIN_PROVIDER.SMS_PASSWORDLESS, login_hint: typeof result === "string" ? result : number, name: "Mobile" },
            });
        }
        setIsValidInput(false);
        return undefined;
    });
    useEffect(() => {
        const getLocation = () => __awaiter(this, void 0, void 0, function* () {
            const result = yield getUserCountry(web3AuthNetwork);
            if (result && result.dialCode) {
                setCountryCode(result.dialCode);
            }
        });
        if (isSmsVisible)
            getLocation();
    }, [isSmsVisible, web3AuthNetwork]);
    const handleInputChange = (e) => {
        setFieldValue(e.target.value);
        if (isValidInput === false)
            setIsValidInput(null);
    };
    const handleInputBiuChange = (e) => {
        const value = e.target.value.trim().toLowerCase();
        setBiuValue(value);
        // eslint-disable-next-line no-console
        console.log(parseInput(`${value}.biu`));
        if (!parseInput(`${value}.biu`).isValid) {
            setBiuValid(false);
        }
        bns
            .getAvailable(`${value.trim()}.biu`)
            .then((res) => {
            // eslint-disable-next-line no-console
            console.log("aaa", res);
            if (!res) {
                setBiuValid(false);
            }
            return true;
        })
            .catch(() => {
            setBiuValid(false);
        });
    };
    const placeholder = useMemo(() => {
        if (isEmailVisible && isSmsVisible)
            return "+(00)123456/name@example.com";
        if (isEmailVisible)
            return "name@example.com";
        return "+(00)123456";
    }, [isEmailVisible, isSmsVisible]);
    return (_jsxs("div", Object.assign({ className: "w3ajs-passwordless w3a-group w3a-group--passwordless" }, { children: [_jsx("div", Object.assign({ className: "w3a-group__title" }, { children: isSmsVisible && (_jsxs("div", Object.assign({ className: "relative flex flex-col items-center cursor-pointer group" }, { children: [_jsx(Icon, { iconName: `information-circle${isDark ? "-light" : ""}` }), _jsxs("div", Object.assign({ className: "absolute z-20 flex-col items-center hidden mb-5 top-4 group-hover:flex" }, { children: [_jsx("div", { className: "w-3 h-3 ml-[3px] -mb-2 rotate-45 bg-app-gray-50 dark:bg-app-gray-600" }), _jsxs("div", Object.assign({ className: "relative p-4 w-[200px] text-xs leading-none text-white rounded-md bg-app-gray-50 dark:bg-app-gray-600 shadow-lg" }, { children: [_jsx("div", Object.assign({ className: "mb-1 text-xs font-medium text-app-gray-900 dark:text-white" }, { children: t("modal.popup.phone-header") })), _jsx("div", Object.assign({ className: "text-xs text-app-gray-400" }, { children: t("modal.popup.phone-body") }))] }))] }))] }))) })), _jsxs("form", Object.assign({ className: "w3ajs-passwordless-form", onSubmit: (e) => handleFormSubmit(e) }, { children: [_jsxs("div", Object.assign({ className: "w3a-biu-wrap" }, { children: [_jsx("span", Object.assign({ className: "w3a-biubiu-prefix" }, { children: "biubiu.id/" })), _jsx("input", { autoComplete: "off", className: "w-full w3a-text-field pd106", name: "bns", required: true, placeholder: ".biu", onChange: (e) => handleInputBiuChange(e), onBlur: (e) => localStorage.setItem("temporaryName", e.target.value) }), biValue && biuValid === false && (_jsx("div", Object.assign({ style: { marginTop: "-10px", marginBottom: "10px" }, className: "w3a-sms-field--error" }, { children: t("unavailable biubiu.id") }))), _jsxs("span", Object.assign({ className: "w3a-input-status" }, { children: [biValue && biuValid && _jsx(Icon, { iconName: "success" }), biValue && !biuValid && _jsx(Icon, { iconName: "failed" })] }))] })), _jsx("input", { className: "w-full mb-4 w3a-text-field", autoComplete: "off", name: "passwordless-input", required: true, placeholder: `${t("modal.social.sms-placeholder-text")} ${placeholder}`, onFocus: (e) => (e.target.placeholder = ""), onBlur: (e) => (e.target.placeholder = `${t("modal.social.sms-placeholder-text")} ${placeholder}`), onChange: (e) => handleInputChange(e) }), isValidInput === false && _jsx("div", Object.assign({ className: "w3a-sms-field--error" }, { children: t("modal.errors-invalid-number-email") })), _jsx("button", Object.assign({ style: { marginTop: "26px" }, disabled: fieldValue === "", className: `w3a-button ${isPrimaryBtn ? "w3a-button--primary" : ""} w-full`, type: "submit" }, { children: t("modal.social.passwordless-cta") }))] }))] })));
}
//# sourceMappingURL=SocialLoginPasswordless.js.map