import { a as __awaiter } from './tslib.es6-ab63fd84.js';
import { create } from 'zustand';
import { g as getUserInfo } from './index-9ddd1558.js';
import { parsePhoneNumber } from 'react-phone-number-input';
import { B as BEARER_TOKEN_COOKIE } from './index-a8162282.js';
import { getCookie } from './miscCookieHelper.js';

const mergePhone = (phone, areaCode) => {
    const processedAreaCode = areaCode.startsWith('+') ? areaCode : `+${areaCode}`;
    const processedPhone = phone.startsWith('0') ? phone.slice(1) : phone;
    return `${processedAreaCode}${processedPhone}`;
};
const splitPhone = (phone) => {
    if (!phone)
        return { areaCode: undefined, phoneNumber: undefined };
    const parsedPhone = parsePhoneNumber(phone);
    return {
        areaCode: parsedPhone.countryCallingCode
            ? '+' + parsedPhone.countryCallingCode
            : '',
        phoneNumber: parsedPhone.nationalNumber || '',
    };
};

var SSOStepTypeType;
(function (SSOStepTypeType) {
    SSOStepTypeType["FIRST"] = "first";
    SSOStepTypeType["WHATSAPP_PHONE_VERIFY"] = "whatsapp_phone_verify";
    SSOStepTypeType["WHATSAPP_OTP"] = "whatsapp_otp";
    SSOStepTypeType["EMAIL"] = "email";
    SSOStepTypeType["VERIFY_PHONE"] = "verify_phone";
    SSOStepTypeType["PASSWORD"] = "password";
    SSOStepTypeType["UPDATE_EMAIL"] = "update_email";
    SSOStepTypeType["FORGOT_PASSWORD_PHONE"] = "forgot_password_phone";
    SSOStepTypeType["FORGOT_PASSWORD_SETUP"] = "forgot_password_setup";
    SSOStepTypeType["OTP"] = "otp";
    SSOStepTypeType["SETUP_FULL"] = "setup_full";
})(SSOStepTypeType || (SSOStepTypeType = {}));
// export const SSOStepsProvider = ({
//   children,
//   defaultSteps,
// }: {
//   children: ReactNode
//   defaultSteps?: SSOStepType[]
// }) => {
//   const [steps, setSteps] = useState<SSOStepType[]>(
//     defaultSteps || [
//       {
//         type: SSOStepTypeType.FIRST,
//       },
//     ],
//   )
//   const [currentStepIndex, setCurrentStepIndex] = useState(0)
//   const [shareData, setShareData] = useState<SSOShareDataType>({})
//   return (
//     <SSOStepsContext.Provider
//       value={{
//         currentStepIndex,
//         steps,
//         setSteps,
//         addStep: (step: SSOStepType) => {
//           setSteps((s) => [...s, step])
//         },
//         goNext: () => {
//           setCurrentStepIndex((index) => index + 1)
//         },
//         goBack: () => {
//           setCurrentStepIndex((index) => index - 1)
//           // remove step when go back
//           setSteps((steps) => steps.slice(0, steps.length - 1))
//         },
//         shareData,
//         setShareData,
//       }}
//     >
//       {children}
//     </SSOStepsContext.Provider>
//   )
// }
const useSSOSteps = create((set) => ({
    currentStepIndex: 0,
    steps: [
        {
            type: SSOStepTypeType.FIRST,
        },
    ],
    setSteps: (s) => set((state) => ({ steps: typeof s === 'function' ? s(state.steps) : s })),
    addStep: (step) => {
        set((state) => ({
            steps: [...state.steps, step],
        }));
    },
    goNext: () => {
        set((state) => ({ currentStepIndex: state.currentStepIndex + 1 }));
    },
    goBack: () => {
        set((state) => ({
            currentStepIndex: state.currentStepIndex - 1,
            steps: state.steps.slice(0, state.steps.length - 1),
        }));
    },
}));

const useSSOV2Store = create()((set, get) => ({
    isHaveReadAndAgreePolicy: false,
    setIsHaveReadAndAgreePolicy: (isHaveReadAndAgreePolicy) => set({ isHaveReadAndAgreePolicy }),
    isGetUpdateFromHHG: false,
    setIsGetUpdateFromHHG: (isGetUpdateFromHHG) => set({ isGetUpdateFromHHG }),
    userInfo: undefined,
    abTestFlow: 'A',
    setABTestFlow(abTestFlow) {
        set({ abTestFlow });
    },
    setUserInfo: (userInfo) => set({ userInfo }),
    isOpen: false,
    setOpen: (isOpen) => set({ isOpen }),
    returnUrl: undefined,
    setReturnUrl: (returnUrl) => set({ returnUrl }),
    mounted: false,
    setMounted: (mounted) => set({ mounted }),
    source: undefined,
    setSource: (source) => set({ source }),
    setupSource: undefined,
    setSetupSource: (setupSource) => set({ setupSource }),
    setOnCloseProp: (onClose) => set({ onCloseProp: onClose }),
    triggerLogin: (params) => {
        var _a, _b;
        const { source, returnUrl } = params || {};
        const alreadyHasToken = getCookie(BEARER_TOKEN_COOKIE);
        if (alreadyHasToken) {
            redirect(params === null || params === void 0 ? void 0 : params.returnUrl, params === null || params === void 0 ? void 0 : params.source, params === null || params === void 0 ? void 0 : params.forceReloadOnClose);
            set({
                isOpen: false,
            });
            (_b = (_a = get()).onCloseProp) === null || _b === void 0 ? void 0 : _b.call(_a);
        }
        else {
            useSSOSteps.setState({
                steps: [
                    {
                        type: SSOStepTypeType.FIRST,
                        config: {
                            legalTextType: ((returnUrl === null || returnUrl === void 0 ? void 0 : returnUrl.includes('joincommunity=1'))
                                ? 'community'
                                : params === null || params === void 0 ? void 0 : params.legalTextType) || 'default',
                        },
                    },
                ],
                currentStepIndex: 0,
            });
            set({
                isOpen: true,
                returnUrl,
                source,
                overrideClose: undefined,
                forceReloadOnClose: (returnUrl === null || returnUrl === void 0 ? void 0 : returnUrl.includes('joincommunity=1'))
                    ? true
                    : (params === null || params === void 0 ? void 0 : params.forceReloadOnClose) || false,
                flowData: undefined,
                userInfo: undefined,
            });
        }
    },
    triggerWhatsappLogin: (params) => {
        const { source, returnUrl, referrer, forceReloadOnClose, isAlreadyLogin, phone_number, area_code, } = params || {};
        const skipPhoneStep = isAlreadyLogin && phone_number && area_code;
        if (skipPhoneStep) {
            const phone = mergePhone(String(phone_number), area_code);
            useSSOSteps.setState({
                steps: [
                    {
                        type: SSOStepTypeType.WHATSAPP_OTP,
                        config: {
                            phone,
                            referrer,
                            useAuthenticatedWhatsAppApis: true,
                        },
                    },
                ],
                currentStepIndex: 0,
            });
        }
        else {
            useSSOSteps.setState({
                steps: [
                    {
                        type: SSOStepTypeType.WHATSAPP_PHONE_VERIFY,
                        config: Object.assign({ referrer }, (isAlreadyLogin
                            ? { useAuthenticatedWhatsAppApis: true }
                            : {})),
                    },
                ],
                currentStepIndex: 0,
            });
        }
        set({
            isOpen: true,
            returnUrl,
            source,
            overrideClose: undefined,
            forceReloadOnClose: forceReloadOnClose || false,
            flowData: { method: 'whatsapp', flow: 'login' },
            userInfo: undefined,
        });
    },
    triggerCareEmailPhoneVerify: (params) => __awaiter(void 0, void 0, void 0, function* () {
        var _a, _b, _c;
        const userInfo = yield getUserInfo();
        if ((_a = userInfo === null || userInfo === void 0 ? void 0 : userInfo._data) === null || _a === void 0 ? void 0 : _a.first_time_login) {
            userInfo._data.first_time_login = 0;
        }
        set({ userInfo: userInfo === null || userInfo === void 0 ? void 0 : userInfo._data });
        const forceUpdatePhoneEmail = (alreadyLoggedIn) => __awaiter(void 0, void 0, void 0, function* () {
            var _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s, _t;
            const userInfo = yield getUserInfo();
            const emailFromProfile = (_d = userInfo === null || userInfo === void 0 ? void 0 : userInfo._data) === null || _d === void 0 ? void 0 : _d.email;
            const usableEmailFromProfile = emailFromProfile &&
                !emailFromProfile.endsWith('@hhg.com') &&
                !emailFromProfile.endsWith('@facebook.com')
                ? emailFromProfile
                : undefined;
            const carriedEmail = (params === null || params === void 0 ? void 0 : params.email) || usableEmailFromProfile;
            const hasPhone = !!((_e = userInfo === null || userInfo === void 0 ? void 0 : userInfo._data) === null || _e === void 0 ? void 0 : _e.phone) && !!((_f = userInfo === null || userInfo === void 0 ? void 0 : userInfo._data) === null || _f === void 0 ? void 0 : _f.phone_verified_at);
            const hasEmail = !!((_g = userInfo === null || userInfo === void 0 ? void 0 : userInfo._data) === null || _g === void 0 ? void 0 : _g.email) &&
                !!((_h = userInfo === null || userInfo === void 0 ? void 0 : userInfo._data) === null || _h === void 0 ? void 0 : _h.email_verified_at) &&
                !((_k = (_j = userInfo === null || userInfo === void 0 ? void 0 : userInfo._data) === null || _j === void 0 ? void 0 : _j.email) === null || _k === void 0 ? void 0 : _k.endsWith('@hhg.com')) &&
                !((_m = (_l = userInfo === null || userInfo === void 0 ? void 0 : userInfo._data) === null || _l === void 0 ? void 0 : _l.email) === null || _m === void 0 ? void 0 : _m.endsWith('@facebook.com'));
            const hasName = !!((_o = userInfo === null || userInfo === void 0 ? void 0 : userInfo._data) === null || _o === void 0 ? void 0 : _o.name);
            const hasBirthday = !!((_p = userInfo === null || userInfo === void 0 ? void 0 : userInfo._data) === null || _p === void 0 ? void 0 : _p.birthday);
            const hasGender = typeof ((_q = userInfo === null || userInfo === void 0 ? void 0 : userInfo._data) === null || _q === void 0 ? void 0 : _q.gender) === 'number';
            const provider = (_r = userInfo === null || userInfo === void 0 ? void 0 : userInfo._data) === null || _r === void 0 ? void 0 : _r.provider;
            const finishedSetup = hasName && hasBirthday && hasGender;
            if (!hasPhone || !hasEmail) {
                useSSOSteps.setState({
                    steps: [
                        {
                            type: !hasPhone
                                ? SSOStepTypeType.VERIFY_PHONE
                                : SSOStepTypeType.UPDATE_EMAIL,
                            config: !hasPhone && !hasEmail
                                ? {
                                    provider,
                                    afterAction: 'update-email',
                                    email: carriedEmail,
                                }
                                : {
                                    provider,
                                    afterAction: !(params === null || params === void 0 ? void 0 : params.skipForceSetup) ? 'setup' : 'done',
                                    email: carriedEmail,
                                },
                        },
                    ],
                    currentStepIndex: 0,
                });
                set((s) => (Object.assign({ source: params === null || params === void 0 ? void 0 : params.source, returnUrl: params === null || params === void 0 ? void 0 : params.returnUrl, isOpen: true, overrideClose: undefined, forceReloadOnClose: true }, (alreadyLoggedIn && !s.flowData
                    ? { flowData: getSSOFlowFromUserProfile(userInfo === null || userInfo === void 0 ? void 0 : userInfo._data) }
                    : {}))));
            }
            else if (!(params === null || params === void 0 ? void 0 : params.skipForceSetup) && !finishedSetup) {
                useSSOSteps.setState({
                    steps: [
                        {
                            type: SSOStepTypeType.SETUP_FULL,
                            config: {
                                userInfo: userInfo._data,
                            },
                        },
                    ],
                    currentStepIndex: 0,
                });
                set((s) => (Object.assign({ source: params === null || params === void 0 ? void 0 : params.source, returnUrl: params === null || params === void 0 ? void 0 : params.returnUrl, isOpen: true, overrideClose: undefined, forceReloadOnClose: true }, (alreadyLoggedIn && !s.flowData
                    ? { flowData: getSSOFlowFromUserProfile(userInfo === null || userInfo === void 0 ? void 0 : userInfo._data) }
                    : {}))));
            }
            else {
                redirect(params === null || params === void 0 ? void 0 : params.returnUrl, params === null || params === void 0 ? void 0 : params.source, true);
                set({
                    isOpen: false,
                    forceReloadOnClose: false,
                });
                (_t = (_s = get()).onCloseProp) === null || _t === void 0 ? void 0 : _t.call(_s);
            }
        });
        if (!((_b = userInfo === null || userInfo === void 0 ? void 0 : userInfo._data) === null || _b === void 0 ? void 0 : _b.id)) {
            useSSOSteps.setState({
                steps: [
                    {
                        type: SSOStepTypeType.FIRST,
                        config: {
                            legalTextType: (((_c = params === null || params === void 0 ? void 0 : params.returnUrl) === null || _c === void 0 ? void 0 : _c.includes('joincommunity=1'))
                                ? 'community'
                                : params === null || params === void 0 ? void 0 : params.legalTextType) || 'default',
                        },
                    },
                ],
                currentStepIndex: 0,
            });
            set({
                isOpen: true,
                overrideClose: forceUpdatePhoneEmail,
                source: params === null || params === void 0 ? void 0 : params.source,
                returnUrl: params === null || params === void 0 ? void 0 : params.returnUrl,
                forceReloadOnClose: true,
                flowData: undefined,
            });
            return;
        }
        else {
            forceUpdatePhoneEmail(true);
        }
    }),
    triggerCommunityEmailVerify: (params) => __awaiter(void 0, void 0, void 0, function* () {
        var _u, _v, _w;
        const userInfo = yield getUserInfo();
        if ((_u = userInfo === null || userInfo === void 0 ? void 0 : userInfo._data) === null || _u === void 0 ? void 0 : _u.first_time_login) {
            userInfo._data.first_time_login = 0;
        }
        set({ userInfo: userInfo === null || userInfo === void 0 ? void 0 : userInfo._data });
        const forceUpdateEmail = (alreadyLoggedIn) => __awaiter(void 0, void 0, void 0, function* () {
            var _x, _y, _z, _0, _1, _2, _3, _4, _5, _6, _7, _8;
            const userInfo = yield getUserInfo();
            const hasEmail = !!((_x = userInfo === null || userInfo === void 0 ? void 0 : userInfo._data) === null || _x === void 0 ? void 0 : _x.email) &&
                !!((_y = userInfo === null || userInfo === void 0 ? void 0 : userInfo._data) === null || _y === void 0 ? void 0 : _y.email_verified_at) &&
                !((_0 = (_z = userInfo === null || userInfo === void 0 ? void 0 : userInfo._data) === null || _z === void 0 ? void 0 : _z.email) === null || _0 === void 0 ? void 0 : _0.endsWith('@hhg.com')) &&
                !((_2 = (_1 = userInfo === null || userInfo === void 0 ? void 0 : userInfo._data) === null || _1 === void 0 ? void 0 : _1.email) === null || _2 === void 0 ? void 0 : _2.endsWith('@facebook.com'));
            const hasName = !!((_3 = userInfo === null || userInfo === void 0 ? void 0 : userInfo._data) === null || _3 === void 0 ? void 0 : _3.name);
            const hasBirthday = !!((_4 = userInfo === null || userInfo === void 0 ? void 0 : userInfo._data) === null || _4 === void 0 ? void 0 : _4.birthday);
            const hasGender = typeof ((_5 = userInfo === null || userInfo === void 0 ? void 0 : userInfo._data) === null || _5 === void 0 ? void 0 : _5.gender) === 'number';
            const provider = (_6 = userInfo === null || userInfo === void 0 ? void 0 : userInfo._data) === null || _6 === void 0 ? void 0 : _6.provider;
            const finishedSetup = hasName && hasBirthday && hasGender;
            if (!hasEmail) {
                useSSOSteps.setState({
                    steps: [
                        {
                            type: SSOStepTypeType.UPDATE_EMAIL,
                            config: {
                                provider,
                                afterAction: 'setup',
                            },
                        },
                    ].filter(Boolean),
                    currentStepIndex: 0,
                });
                set((s) => (Object.assign({ source: params === null || params === void 0 ? void 0 : params.source, returnUrl: params === null || params === void 0 ? void 0 : params.returnUrl, isOpen: true, overrideClose: undefined, forceReloadOnClose: (params === null || params === void 0 ? void 0 : params.forceReloadOnClose) || false }, (alreadyLoggedIn && !s.flowData
                    ? { flowData: getSSOFlowFromUserProfile(userInfo === null || userInfo === void 0 ? void 0 : userInfo._data) }
                    : {}))));
            }
            else if (!finishedSetup) {
                useSSOSteps.setState({
                    steps: [
                        {
                            type: SSOStepTypeType.SETUP_FULL,
                            config: {
                                userInfo: userInfo._data,
                            },
                        },
                    ],
                    currentStepIndex: 0,
                });
                set((s) => (Object.assign({ source: params === null || params === void 0 ? void 0 : params.source, returnUrl: params === null || params === void 0 ? void 0 : params.returnUrl, isOpen: true, overrideClose: undefined, forceReloadOnClose: true }, (alreadyLoggedIn && !s.flowData
                    ? { flowData: getSSOFlowFromUserProfile(userInfo === null || userInfo === void 0 ? void 0 : userInfo._data) }
                    : {}))));
            }
            else {
                redirect(params === null || params === void 0 ? void 0 : params.returnUrl, params === null || params === void 0 ? void 0 : params.source, true);
                set({
                    isOpen: false,
                    forceReloadOnClose: false,
                });
                (_8 = (_7 = get()).onCloseProp) === null || _8 === void 0 ? void 0 : _8.call(_7);
            }
        });
        if (!((_v = userInfo === null || userInfo === void 0 ? void 0 : userInfo._data) === null || _v === void 0 ? void 0 : _v.id)) {
            useSSOSteps.setState({
                steps: [
                    {
                        type: SSOStepTypeType.FIRST,
                        config: {
                            legalTextType: (((_w = params === null || params === void 0 ? void 0 : params.returnUrl) === null || _w === void 0 ? void 0 : _w.includes('joincommunity=1'))
                                ? 'community'
                                : params === null || params === void 0 ? void 0 : params.legalTextType) || 'default',
                        },
                    },
                ],
                currentStepIndex: 0,
            });
            set({
                isOpen: true,
                overrideClose: forceUpdateEmail,
                source: params === null || params === void 0 ? void 0 : params.source,
                returnUrl: params === null || params === void 0 ? void 0 : params.returnUrl,
                forceReloadOnClose: true,
                flowData: undefined,
            });
            return;
        }
        else {
            forceUpdateEmail(true);
        }
    }),
    forceReloadOnClose: false,
}));
const redirect = (returnUrl, source, forceReload) => {
    if (forceReload) {
        let newReturnUrl;
        if ((returnUrl === null || returnUrl === void 0 ? void 0 : returnUrl.startsWith('http')) || (returnUrl === null || returnUrl === void 0 ? void 0 : returnUrl.startsWith('//'))) {
            newReturnUrl = new URL(returnUrl);
        }
        else if (returnUrl) {
            newReturnUrl = new URL(returnUrl, window.location.href);
        }
        else {
            newReturnUrl = new URL(window.location.href);
        }
        if (source) {
            newReturnUrl.searchParams.set('source', source);
        }
        window.location.href = newReturnUrl.href;
        return true;
    }
    const currentUrl = new URL(window.location.href);
    if (returnUrl) {
        let newReturnUrl;
        if (returnUrl.startsWith('http') || returnUrl.startsWith('//')) {
            newReturnUrl = new URL(returnUrl);
        }
        else {
            newReturnUrl = new URL(returnUrl, window.location.href);
        }
        const paramSource = newReturnUrl.searchParams.get('source');
        currentUrl.searchParams.delete('source');
        newReturnUrl.searchParams.delete('source');
        // delete source from both url so we can compare and readd source later if needed
        const _source = paramSource || source;
        if (currentUrl.href !== newReturnUrl.href) {
            if (_source) {
                newReturnUrl.searchParams.set('source', _source || '');
            }
            window.location.href = newReturnUrl.href;
            return true;
        }
    }
    if (source) {
        currentUrl.searchParams.set('source', source);
        window.history.replaceState({}, '', currentUrl.href);
        return;
    }
};
const SSOV2_LOCALES = ['vi-VN', 'id-ID', 'ms-MY'];
const IS_SSOV2_ENABLED = (locale) => {
    return (!process.env.NEXT_PUBLIC_MARRY_BABY &&
        SSOV2_LOCALES.includes(locale ||
            process.env.UNIFY_LOCALE ||
            process.env.NEXT_PUBLIC_DEPLOY_LOCALE ||
            ''));
};
const getSSOFlowFromUserProfile = (userInfo) => {
    if (!userInfo)
        throw new Error('userInfo is required');
    const hasName = !!(userInfo === null || userInfo === void 0 ? void 0 : userInfo.name);
    const hasBirthday = !!(userInfo === null || userInfo === void 0 ? void 0 : userInfo.birthday);
    const hasGender = typeof (userInfo === null || userInfo === void 0 ? void 0 : userInfo.gender) === 'number';
    const finishedSetup = hasName && hasBirthday && hasGender;
    return {
        flow: finishedSetup ? 'signup' : 'login',
        method: (userInfo === null || userInfo === void 0 ? void 0 : userInfo.provider) || 'email',
    };
};
const isUserFinishedSetup = (userInfo) => {
    if (!userInfo)
        throw new Error('userInfo is required');
    const hasName = !!(userInfo === null || userInfo === void 0 ? void 0 : userInfo.name);
    const hasBirthday = !!(userInfo === null || userInfo === void 0 ? void 0 : userInfo.birthday);
    const hasGender = typeof (userInfo === null || userInfo === void 0 ? void 0 : userInfo.gender) === 'number';
    return hasName && hasBirthday && hasGender;
};
const isFlowFinishedSetup = (flowData) => {
    var _a, _b, _c;
    return (((_a = flowData === null || flowData === void 0 ? void 0 : flowData.metaData) === null || _a === void 0 ? void 0 : _a.is_gender) &&
        ((_b = flowData === null || flowData === void 0 ? void 0 : flowData.metaData) === null || _b === void 0 ? void 0 : _b.is_name) &&
        ((_c = flowData === null || flowData === void 0 ? void 0 : flowData.metaData) === null || _c === void 0 ? void 0 : _c.is_birthday));
};
const isPhoneNotVerifedYet = (userInfo) => {
    return !(userInfo === null || userInfo === void 0 ? void 0 : userInfo.phone_verified_at) || !(userInfo === null || userInfo === void 0 ? void 0 : userInfo.phone);
};
const isLoginWithPhoneNotVerifedYet = (flowData, userInfo) => {
    return ((flowData === null || flowData === void 0 ? void 0 : flowData.flow) === 'login' &&
        (userInfo === null || userInfo === void 0 ? void 0 : userInfo.phone) &&
        (userInfo === null || userInfo === void 0 ? void 0 : userInfo.area_code) &&
        !(userInfo === null || userInfo === void 0 ? void 0 : userInfo.phone_verified_at));
};

export { IS_SSOV2_ENABLED as I, SSOStepTypeType as S, useSSOSteps as a, isPhoneNotVerifedYet as b, isLoginWithPhoneNotVerifedYet as c, isFlowFinishedSetup as d, isUserFinishedSetup as i, redirect as r, splitPhone as s, useSSOV2Store as u };
