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, useRef, 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";
var BiuStatus;
(function (BiuStatus) {
    BiuStatus["Available"] = "Available";
    BiuStatus["Unavailable"] = "Unavailable";
    BiuStatus["TooShort"] = "TooShort";
    BiuStatus["Registered"] = "registered";
    BiuStatus["Loading"] = "Loading";
    BiuStatus["UnOpen"] = "unOpen";
    BiuStatus["Appointment"] = "Appointment";
})(BiuStatus || (BiuStatus = {}));
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 [biuValue, setBiuValue] = useState("");
    const [biuStatus, setBiuStatus] = useState(BiuStatus.Available);
    const [loading, setLoading] = useState(false);
    const bns = BNSContext();
    const [t] = useTranslation();
    const inputRef = useRef(null);
    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 getAppointment = (name) => __awaiter(this, void 0, void 0, function* () {
        const res = yield fetch("https://biubiu.id/ens/has_appointment", {
            method: "POST",
            headers: {
                "Content-Type": "application/json",
            },
            body: JSON.stringify({
                ens: name,
                operationID: `${Date.now()}`,
            }),
        });
        if (res) {
            const status = yield res.json();
            return status.data;
        }
        return false;
    });
    const failedTip = useMemo(() => {
        switch (biuStatus) {
            case BiuStatus.Available:
                return t("modal.ens.Available");
            case BiuStatus.UnOpen:
                return t("modal.ens.Notyetopen");
            case BiuStatus.Unavailable:
                return t("modal.ens.InvalidFormatforName");
            case BiuStatus.TooShort:
                return t("modal.ens.TooShort");
            case BiuStatus.Loading:
                return t("modal.ens.Inquiring");
            case BiuStatus.Registered:
                return t("modal.ens.Registered");
            case BiuStatus.Appointment:
                return t("modal.ens.appointed");
            default:
                return t("modal.ens.Inquiring");
        }
    }, [biuValue, biuStatus]);
    // eslint-disable-next-line consistent-return
    const handleInputBiuChange = (e) => {
        const value = e.target.value.trim().toLowerCase();
        setLoading(true);
        setBiuValue(value);
        if (value.length < 3) {
            setBiuStatus(BiuStatus.TooShort);
            return false;
        }
        Promise.all([bns.getValid(`${value}.biu`), bns.getAvailable(`${value.trim()}.biu`), getAppointment(`${value}.biu`)])
            .then(([valid, available, appointed]) => {
            setLoading(false);
            if (!parseInput(`${value}.biu`).isValid) {
                setBiuStatus(BiuStatus.Unavailable);
                return false;
            }
            if (!valid) {
                setBiuStatus(BiuStatus.UnOpen);
                return false;
            }
            if (appointed) {
                setBiuStatus(BiuStatus.Appointment);
                return false;
            }
            if (available && valid) {
                localStorage.setItem("temporaryName", value);
                setBiuStatus(BiuStatus.Available);
                return false;
            }
            if (valid && !available) {
                setBiuStatus(BiuStatus.Registered);
                return false;
            }
            setBiuStatus(BiuStatus.Available);
            localStorage.setItem("temporaryName", value);
            return true;
        })
            .catch(() => {
            setLoading(false);
            setBiuStatus(BiuStatus.Unavailable);
            return false;
        });
    };
    useEffect(() => {
        const temporaryName = localStorage.getItem("temporaryName");
        if (temporaryName && inputRef.current) {
            inputRef.current.value = temporaryName;
            handleInputBiuChange({ target: { value: inputRef.current.value } });
        }
    }, [inputRef]);
    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", { ref: inputRef, autoComplete: "off", className: "w-full w3a-text-field pd106", name: "bns", placeholder: ".biu", onBlur: (e) => handleInputBiuChange(e) }), !loading && biuValue && biuStatus !== BiuStatus.Available && (_jsx("div", Object.assign({ style: { marginTop: "-10px", marginBottom: "10px" }, className: "w3a-sms-field--error" }, { children: failedTip }))), _jsxs("span", Object.assign({ className: "w3a-input-status" }, { children: [loading && biuValue && (_jsxs("div", Object.assign({ style: { width: "14px", height: "14px", position: "absolute" }, className: "w3ajs-modal-loader__spinner w3a-spinner" }, { children: [_jsx("div", { style: { width: "0", height: 0 }, className: "w3a-spinner__head" }), _jsx("div", { style: { width: "4px", height: "4px" }, className: "w3a-spinner__mask" })] }))), !loading && biuValue && biuStatus === BiuStatus.Available && _jsx(Icon, { iconName: "success" }), !loading && biuValue && biuStatus !== BiuStatus.Available && _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