import React__default, { createContext, useContext, useMemo, useCallback, useState, useEffect, forwardRef, useRef } from 'react';
import { rem, Container, createStyles, Box, Stack, Flex, AspectRatio, ScrollArea, Chip, Group, Badge, MultiSelect, Stepper } from '@mantine/core';
import { C as CommonGAssets } from './index-43584299.js';
import { e as callApiWithAuth, f as getApiPath, T as TogetherComponentGlobalContext, h as getPremiumApiPath, i as getWebsiteUrlApi, j as getSsoApiPath } from './utils-f5ed68ed.js';
import { G as GA_TOKEN_COOKIE } from './index-a8162282.js';
import { H as HEALTH_TOOL_TYPE, a as HEALTH_TOOL_DEFAULT_IMG } from './healthTools-304323dc.js';
import { RISK_SCREENER_NAME, RISK_SCREENER_SLUG } from './constantsRiskScreener.js';
import { _ as __rest, a as __awaiter } from './tslib.es6-ab63fd84.js';
import { u as useSSOV2Store, I as IS_SSOV2_ENABLED } from './store-b88d97b9.js';
import { I as ImageWrap } from './index-74fcf0aa.js';
import { g as getCurrentBaseUrl, a as getCurrentSsoUrl } from './normalizeLink-0bc93fbf.js';
import { u as useTranslations } from './index-960c3169.js';
import { useForm, isNotEmpty } from '@mantine/form';
import { d as Checkbox, g as ChipButton, I as Input, c as AspectRatio$1 } from './index-c3177e04.js';
import '@mantine/dates';
import './index-91c6a49c.js';
import { t as themeColors } from './index-4e6b8a2b.js';
import { T as Text } from './index-d0a1200e.js';
import { B as Button } from './index-f71a880f.js';
import './index-38e03570.js';
import './index.styles-3ba274d2.js';
import { useViewportSize } from '@mantine/hooks';
import './utils-32d7d5af.js';
import './index-f21110d2.js';
import { PATHS as PATHS$2 } from './togetherApiPaths.js';
import './translationsContext-4de1415e.js';
import { H as Heading } from './index-afe90ec2.js';
import { u as useHealthToolsCache } from './useHealthToolCache-872bf831.js';
import { I as Icon } from './index-51f58c70.js';
import { domainLocales } from './constantsDomainLocales.js';
import { isProduction } from './constantsIsProduction.js';
import { Close, Plus } from '@hhgtech/icons/core';
import { i as isVideo } from './index-3942e08c.js';
import { M as Modal } from './index-7601f2a1.js';
import Cookies from 'js-cookie';
import flatten from 'lodash/flatten';
import uniqBy from 'lodash/uniqBy';
import { L as LOCALE } from './Locale-87b46912.js';

const PREFER_TOPICS = [
    {
        title: 'Health News & Current Affairs',
        description: 'Covering the latest happenings in the health field, including medical breakthroughs, policies, and disease outbreaks',
        icon: CommonGAssets.getAssetPath('newsletter-prefer/newsletter-health.svg'),
        checked: false,
        id: 1,
    },
    {
        title: 'Educational Medical Hello Bacsi Content',
        description: 'Covering the latest happenings in the health field, including medical breakthroughs, policies, and disease outbreaks',
        icon: CommonGAssets.getAssetPath('newsletter-prefer/newsletter-education.svg'),
        checked: false,
        id: 2,
    },
    {
        title: 'Hello Health Community Feed',
        description: 'Covering the latest happenings in the health field, including medical breakthroughs, policies, and disease outbreaks',
        icon: CommonGAssets.getAssetPath('newsletter-prefer/newsletter-community.svg'),
        checked: false,
        id: 3,
    },
];

var BannerCategory;
(function (BannerCategory) {
    BannerCategory["Pregnant"] = "pregnant";
    BannerCategory["Parenting"] = "parenting";
})(BannerCategory || (BannerCategory = {}));
var BannerType;
(function (BannerType) {
    BannerType["Option"] = "option";
})(BannerType || (BannerType = {}));
var OptionBannerStyleType;
(function (OptionBannerStyleType) {
    OptionBannerStyleType["Button"] = "button";
    OptionBannerStyleType["Checkbox"] = "checkbox";
})(OptionBannerStyleType || (OptionBannerStyleType = {}));
var BannerAction;
(function (BannerAction) {
    BannerAction["ShowTool"] = "showTool";
    BannerAction["ShowPremiumModal"] = "showPremiumModal";
    BannerAction["ShowOptionBanner"] = "showOptionBanner";
    BannerAction["Hide"] = "hide";
})(BannerAction || (BannerAction = {}));
const MAPPING_CATEGORY_PREMIUM_TYPE = {
    pregnancy: BannerCategory.Pregnant,
    parenting: BannerCategory.Parenting,
};
const MAPPING_CATEGORY_PREMIUM_API_TYPE = {
    [BannerCategory.Pregnant]: 'pregnant',
    [BannerCategory.Parenting]: 'parent',
};

const FLOW = (t, currentUrl) => ({
    [BannerCategory.Pregnant]: {
        action: BannerAction.ShowOptionBanner,
        props: {
            heading: t('pnBanner.pregnancy.heading'),
            description: t('pnBanner.pregnancy.desc'),
            styleType: OptionBannerStyleType.Button,
            thumbnail: {
                desktop: CommonGAssets.getAssetPath(`newsletter/banner-option-pregnancy-desktop.png`),
                mobile: CommonGAssets.getAssetPath(`newsletter/banner-option-pregnancy-mobile.png`),
            },
            buttonProps: {
                variant: 'white',
                styles: (theme) => ({
                    minWidth: rem(80),
                    [theme.fn.largerThan('sm')]: {
                        minWidth: rem(120),
                    },
                }),
            },
            items: [
                {
                    label: t('switchBtn.yes'),
                    value: 'yes',
                    tracking: {
                        dataEventCategory: 'Focused Audience',
                        dataEventAction: 'Are you navigating the world of pregnancy - Yes Click',
                        dataEventLabel: currentUrl,
                    },
                },
                {
                    label: t('switchBtn.no'),
                    value: 'no',
                    tracking: {
                        dataEventCategory: 'Focused Audience',
                        dataEventAction: 'Are you navigating the world of pregnancy - No Click',
                        dataEventLabel: currentUrl,
                    },
                },
            ],
        },
        submitHandler: {
            yes: {
                action: BannerAction.ShowTool,
                props: {
                    value: HEALTH_TOOL_TYPE.DUE_DATE,
                },
            },
            no: {
                action: BannerAction.ShowPremiumModal,
            },
        },
    },
    [BannerCategory.Parenting]: {
        action: BannerAction.ShowOptionBanner,
        props: {
            heading: t('pnBanner.parenting.heading'),
            description: t('pnBanner.parenting.desc'),
            thumbnail: {
                desktop: CommonGAssets.getAssetPath(`newsletter/banner-option-parenting-desktop.png`),
                mobile: CommonGAssets.getAssetPath(`newsletter/banner-option-parenting-mobile.png`),
            },
            hideDescOnMobile: true,
            styleType: OptionBannerStyleType.Checkbox,
            items: [
                {
                    label: t('pnBanner.toddlers'),
                    value: 'todders',
                },
                {
                    label: t('pnBanner.teenager'),
                    value: 'teenager',
                },
            ],
            submitBtnTracking: {
                dataEventCategory: 'Focused Audience',
                dataEventAction: 'What is the age range of your kids Click',
                dataEventLabel: currentUrl,
            },
        },
        submitHandler: {
            todders: {
                action: BannerAction.ShowTool,
                props: {
                    value: HEALTH_TOOL_TYPE.BABY_VACCINE,
                },
            },
            teenager: {
                action: BannerAction.ShowOptionBanner,
                props: {
                    styleType: OptionBannerStyleType.Button,
                    heading: t('pnBanner.teenager.heading'),
                    description: t('pnBanner.parenting.desc'),
                    thumbnail: {
                        desktop: CommonGAssets.getAssetPath(`newsletter/banner-option-parenting-desktop.png`),
                        mobile: CommonGAssets.getAssetPath(`newsletter/banner-option-parenting-mobile.png`),
                    },
                    buttonProps: {
                        variant: 'white',
                    },
                    items: [
                        {
                            label: t('childCard.boy'),
                            value: 'teenager.boy',
                            tracking: {
                                dataEventCategory: 'Focused Audience',
                                dataEventAction: 'What is the gender of your kids - Boy Click',
                                dataEventLabel: currentUrl,
                            },
                        },
                        {
                            label: t('childCard.girl'),
                            value: 'teenager.girl',
                            tracking: {
                                dataEventCategory: 'Focused Audience',
                                dataEventAction: 'What is the gender of your kids - Girl Click',
                                dataEventLabel: currentUrl,
                            },
                        },
                    ],
                },
            },
            'teenager.boy': {
                action: BannerAction.ShowPremiumModal,
            },
            'teenager.girl': {
                action: BannerAction.ShowTool,
                activeTool: RISK_SCREENER_NAME.HPV,
                props: {
                    value: RISK_SCREENER_NAME.HPV,
                },
            },
            'todders|teenager': {
                action: BannerAction.ShowOptionBanner,
                props: {
                    styleType: OptionBannerStyleType.Button,
                    heading: t('pnBanner.both.heading'),
                    description: t('pnBanner.both.desc'),
                    thumbnail: {
                        desktop: CommonGAssets.getAssetPath(`newsletter/banner-option-parenting-desktop.png`),
                        mobile: CommonGAssets.getAssetPath(`newsletter/banner-option-parenting-mobile.png`),
                    },
                    hideDescOnMobile: true,
                    buttonProps: {
                        variant: 'secondary',
                    },
                    styles: (theme) => ({
                        wrapper: {
                            [theme.fn.smallerThan('sm')]: {
                                flexDirection: 'column',
                            },
                        },
                        button: {
                            background: theme.colors.blue[0],
                        },
                    }),
                    items: [
                        {
                            label: t('pnBanner.vaccine.btnLabel'),
                            activeTool: HEALTH_TOOL_TYPE.BABY_VACCINE,
                            isLink: true,
                            tracking: {
                                dataEventCategory: 'Focused Audience',
                                dataEventAction: 'Experience our tools for parent - Baby Vaccine Click',
                                dataEventLabel: currentUrl,
                            },
                        },
                        {
                            label: t('pnBanner.pn.btnLabel'),
                            value: 'todders|teenager.showPN',
                            isPNBtn: true,
                            tracking: {
                                dataEventCategory: 'Focused Audience',
                                dataEventAction: 'Experience our tools for parent - Premium Newsletter Click',
                                dataEventLabel: currentUrl,
                            },
                        },
                    ],
                },
            },
            'todders|teenager.showPN': {
                action: BannerAction.ShowOptionBanner,
                props: {
                    styleType: OptionBannerStyleType.Button,
                    heading: t('pnBanner.both.heading'),
                    description: t('pnBanner.both.desc'),
                    thumbnail: {
                        desktop: CommonGAssets.getAssetPath(`newsletter/banner-option-parenting-desktop.png`),
                        mobile: CommonGAssets.getAssetPath(`newsletter/banner-option-parenting-mobile.png`),
                    },
                    hideDescOnMobile: true,
                    buttonProps: {
                        variant: 'secondary',
                    },
                    styles: (theme) => ({
                        wrapper: {
                            [theme.fn.smallerThan('sm')]: {
                                flexDirection: 'column',
                            },
                        },
                        button: {
                            background: theme.colors.blue[0],
                        },
                    }),
                    items: [
                        {
                            label: t('pnBanner.vaccine.btnLabel'),
                            activeTool: HEALTH_TOOL_TYPE.BABY_VACCINE,
                            isLink: true,
                            tracking: {
                                dataEventCategory: 'Focused Audience',
                                dataEventAction: 'Experience our tools for parent - Baby Vaccine Click',
                                dataEventLabel: currentUrl,
                            },
                        },
                    ],
                },
            },
        },
    },
});
const TOOL_BANNERS_PROPS = (t) => ({
    [HEALTH_TOOL_TYPE.DUE_DATE]: {
        heading: t('pnBanner.dueDateTool.heading'),
        description: t('pnBanner.dueDateTool.desc'),
        btnLabel: t('pnBanner.caclNow'),
        value: HEALTH_TOOL_TYPE.DUE_DATE,
        dataEventAction: 'Try our Due Date Calculator Click',
    },
    [HEALTH_TOOL_TYPE.BABY_VACCINE]: {
        heading: t('pnBanner.vaccination.heading'),
        description: t('pnBanner.vaccination.desc'),
        btnLabel: t('pnBanner.caclNow'),
        value: HEALTH_TOOL_TYPE.BABY_VACCINE,
        dataEventAction: 'Try our Baby Vaccine Scheduler Click',
    },
    [HEALTH_TOOL_TYPE.BABY_GROWTH]: {
        heading: 'Baby Growth',
        description: t('pnBanner.vaccination.desc'),
        btnLabel: t('pnBanner.caclNow'),
        value: HEALTH_TOOL_TYPE.BABY_GROWTH,
    },
    [RISK_SCREENER_NAME.HPV]: {
        heading: t('pnBanner.hpv.heading'),
        description: t('pnBanner.hpv.desc'),
        thumbnail: {
            desktop: CommonGAssets.getAssetPath(`newsletter/banner-option-hpv-desktop.png`),
            mobile: CommonGAssets.getAssetPath(`newsletter/banner-option-hpv-mobile.png`),
        },
        isRiskScreener: true,
        btnLabel: t('pnBanner.checkNow'),
        value: RISK_SCREENER_NAME.HPV,
        hideDescOnMobile: true,
        dataEventAction: 'Keep safe from HPV virus Click',
    },
});

const SurveyOrPremiumBannerContext = createContext({});

const PnBannerEle = (_a) => {
    var rest = __rest(_a, []);
    const { locale } = useTranslations();
    const { type, isMobile, currentUrl, isMarketing, isLoggedIn, setShouldAcquisitionModalOpen, } = useContext(SurveyOrPremiumBannerContext);
    const { triggerLogin } = useSSOV2Store();
    const bannerClick = () => __awaiter(void 0, void 0, void 0, function* () {
        const url = isMarketing
            ? getCurrentBaseUrl(locale) + '/dang-ky-nhan-tin/'
            : `${window.location.href}?source=acquisition`;
        if (isLoggedIn) {
            setShouldAcquisitionModalOpen === null || setShouldAcquisitionModalOpen === void 0 ? void 0 : setShouldAcquisitionModalOpen();
        }
        else {
            if (IS_SSOV2_ENABLED(locale)) {
                triggerLogin({
                    returnUrl: isMarketing ? url : undefined,
                    source: !isMarketing ? 'acquisition' : undefined,
                });
            }
            else {
                window.location.href = `${getCurrentSsoUrl(locale)}/?returnUrl=${encodeURIComponent(url)}`;
            }
        }
    });
    return (React__default.createElement(Container, Object.assign({ mih: { base: 144, md: 160 }, fluid: true, p: 0, sx: {
            borderRadius: 4,
            cursor: 'pointer',
        }, onClick: bannerClick, "data-event-category": "Newsletter", "data-event-action": "Banner Click", "data-event-label": currentUrl, className: "pointer-event-child-none" }, rest),
        React__default.createElement(ImageWrap, { src: isMarketing
                ? CommonGAssets.getAssetPath(`newsletter/${isMobile ? 'Mobile' : 'Desktop'}_Marketing.png`)
                : CommonGAssets.getAssetPath(`newsletter/${isMobile ? 'Mobile' : 'Desktop'}_${type}.png`), style: { maxWidth: '100%' }, alt: "newsletter banner" })));
};

const PATHS$1 = {
    GET_SUGGESTED_TOPIC: 'api/v1/categories?external_id={externalId}&site={website_url}',
    GET_NEWSLETTER_CATEGORIES: 'api/v1/categories?site={website_url}',
    POST_SUBSCRIPTION: 'api/v1/subscription?site={website_url}',
    TEMP_POST_SUBSCRIPTION: 'api/v1/subscription/temporary?site={website_url}',
    TEMP_POST_SUBSCRIPTION_OFFICIAL: 'api/v1/subscription/official?site={website_url}',
    TEMP_GET_NEWSLETTER_CATEGORIES: 'api/v1/categories/temporary?site={website_url}',
    GET_SUBSCRIPTION_CATEGORIES: 'api/v1/categories?site={website_url}',
};

var useStyles = createStyles((theme) => {
    return {
        root: {},
        wrapper: {
            [theme.fn.smallerThan('sm')]: {
                width: '70%',
            },
        },
        button: {
            [theme.fn.smallerThan('sm')]: {
                height: 'auto',
                minHeight: rem(32),
                padding: `${rem(6)} ${rem(16)}`,
                textAlign: 'center',
                width: '100%',
            },
        },
        buttonLabel: {
            whiteSpace: 'normal',
        },
    };
});

const BannerLayout = ({ heading, description, thumbnail = {
    desktop: '',
    mobile: '',
}, hideDescOnMobile, children, }) => {
    const { isMobile, minHeight } = useContext(SurveyOrPremiumBannerContext);
    return (React__default.createElement(Box, { sx: () => ({
            borderRadius: rem(8),
            background: 'linear-gradient(180deg, #FAFDFF 0%, #E3F2FF 100%)',
        }) },
        React__default.createElement(Box, { sx: (theme) => ({
                minHeight: rem(minHeight),
                borderRadius: 'inherit',
                background: `url(${isMobile ? thumbnail.mobile : thumbnail.desktop})`,
                backgroundPosition: 'center right',
                backgroundRepeat: 'no-repeat',
                backgroundSize: 'contain',
                padding: `${rem(24)} ${rem(16)}`,
                display: 'flex',
                flexDirection: 'column',
                justifyContent: 'center',
                [theme.fn.largerThan('sm')]: {
                    padding: `${rem(22)} ${rem(32)}`,
                },
            }) },
            React__default.createElement(Stack, { spacing: rem(16) },
                React__default.createElement(Stack, { spacing: rem(4), sx: (theme) => ({
                        maxWidth: '60%',
                        [theme.fn.largerThan('sm')]: {
                            maxWidth: '70%',
                        },
                    }) },
                    heading && React__default.createElement(Heading, { tag: "h4" }, heading),
                    !(hideDescOnMobile && isMobile) && description && (React__default.createElement(Text, { size: "p4" }, description))),
                React__default.createElement(Box, null, children)))));
};

const BannerWithOptions = (props) => {
    const { styleType = OptionBannerStyleType.Button, items: itemsProp = [], buttonProps, styles, submitBtnTracking, } = props;
    const { classes } = useStyles(undefined, {
        name: 'PremiumBannerWithOptions',
        styles,
    });
    const { t, locale } = useTranslations();
    const { surveyType, articleId, handleClickOption, hasPremiumBanner, source, isMobile, setShowPNModal, } = useContext(SurveyOrPremiumBannerContext);
    const items = useMemo(() => !hasPremiumBanner
        ? itemsProp.filter((i) => !Boolean(i.isPNBtn)).filter(Boolean)
        : itemsProp, [itemsProp]);
    const { getHealthToolLink } = useHealthToolsCache(locale);
    const form = useForm({
        initialValues: {
            bannerOptions: [],
        },
    });
    const saveStep = (value) => __awaiter(void 0, void 0, void 0, function* () {
        return yield callApiWithAuth(getApiPath(PATHS$2.HEALTH_TOOL.CREATE, {
            _locale: locale,
            type: MAPPING_CATEGORY_PREMIUM_API_TYPE[surveyType],
        }), 'POST', {
            headers: {
                'Content-Type': 'application/json',
            },
            data: {
                value,
                article: articleId,
                source,
            },
        });
    });
    const renderButtonChoice = useCallback(() => (React__default.createElement(Flex, { gap: rem(8), className: classes.wrapper }, items.map((i, idx) => (React__default.createElement(Box, { key: String(idx), component: i.isLink ? 'a' : 'div', href: i.isRiskScreener
            ? `https://${domainLocales[locale]}/bot/${RISK_SCREENER_SLUG[locale][i.activeTool]}/`
            : i.isLink
                ? getHealthToolLink(i.activeTool)
                : undefined },
        React__default.createElement(Button, Object.assign({ className: classes.button, classNames: {
                label: classes.buttonLabel,
            }, size: "sm" }, i.tracking, buttonProps, { onClick: () => {
                if (!i.isLink) {
                    if (i.isPNBtn) {
                        setShowPNModal(true);
                    }
                    saveStep(i.value);
                    handleClickOption(i.value);
                }
            } }), i.label)))))), [items, form]);
    const renderCheckboxChoice = useCallback(() => (React__default.createElement(Flex, null,
        React__default.createElement(Flex, { align: 'center', gap: rem(24), sx: (theme) => ({
                background: 'white',
                borderRadius: rem(8),
                padding: rem(4),
                [theme.fn.largerThan('sm')]: {
                    paddingLeft: rem(16),
                },
            }) },
            React__default.createElement(Checkbox.Group, Object.assign({}, form.getInputProps('bannerOptions', { type: 'checkbox' })),
                React__default.createElement(Flex, { gap: rem(16) }, items.map((i, idx) => (React__default.createElement(Checkbox, { key: String(idx), value: i.value, label: i.label, styles: {
                        label: {
                            cursor: 'pointer',
                        },
                    } }))))),
            React__default.createElement(Button, Object.assign({ size: "sm" }, submitBtnTracking, buttonProps, { disabled: form.getInputProps('bannerOptions').value.length === 0, leftIcon: isMobile ? (React__default.createElement(Icon.ArrowRightTail, { size: 18, useCurrentColor: true })) : undefined, onClick: () => {
                    const curValues = form.getInputProps('bannerOptions').value;
                    saveStep(curValues.join('|'));
                    handleClickOption(curValues.join('|'));
                }, styles: (theme) => ({
                    root: {
                        [theme.fn.smallerThan('sm')]: {
                            width: rem(38),
                            minWidth: 'auto',
                            padding: 0,
                        },
                    },
                }) }), !isMobile && t('pnBanner.submit'))))), [items, form]);
    return (React__default.createElement(BannerLayout, Object.assign({}, props), styleType === OptionBannerStyleType.Button
        ? renderButtonChoice()
        : styleType === OptionBannerStyleType.Checkbox
            ? renderCheckboxChoice()
            : null));
};

const ToolBanner = (props) => {
    var _a, _b;
    const { t } = useTranslations();
    const { heading, description, thumbnail, btnLabel, value, isRiskScreener, hideDescOnMobile, dataEventAction, } = props;
    const { locale } = useTranslations();
    const { isMobile } = useContext(SurveyOrPremiumBannerContext);
    const { getHealthToolLink, allTools } = useHealthToolsCache(locale);
    const layout = isRiskScreener ? 'mainBanner' : 'toolBanner';
    const btnEle = useMemo(() => {
        const toolUrl = isRiskScreener
            ? `https://${!isProduction ? 'discover.' : ''}${domainLocales[locale]}/bot/${RISK_SCREENER_SLUG[locale][value]}`
            : getHealthToolLink(value);
        return (React__default.createElement("a", { href: toolUrl },
            React__default.createElement(Button, { size: "sm", "data-event-category": "Focused Audience", "data-event-action": dataEventAction, "data-event-label": toolUrl }, btnLabel || t('pnBanner.caclNow'))));
    }, [allTools]);
    return layout === 'mainBanner' ? (React__default.createElement(BannerLayout, Object.assign({}, Object.assign(Object.assign({}, props), { thumbnail: props.thumbnail })), btnEle)) : (React__default.createElement(Flex, { gap: rem(7), align: 'center', justify: 'space-between', sx: (theme) => ({
            borderRadius: rem(8),
            background: theme.colors.blue[0],
            minHeight: rem(180),
            padding: `${rem(24)} ${rem(16)}`,
            [theme.fn.largerThan('sm')]: {
                padding: `${rem(34)} ${rem(32)}`,
            },
        }) },
        React__default.createElement(Stack, { spacing: rem(12) },
            React__default.createElement(Stack, { spacing: rem(4) },
                heading && React__default.createElement(Heading, { tag: "h4" }, heading),
                !(isMobile && hideDescOnMobile) && description && (React__default.createElement(Text, { size: "p4" }, description))),
            React__default.createElement(Flex, { gap: rem(8), sx: {
                    button: {
                        minWidth: rem(120),
                    },
                } }, btnEle)),
        React__default.createElement(Flex, { align: 'center', justify: 'center', sx: (theme) => ({
                width: rem(96),
                height: rem(96),
                borderRadius: '50%',
                background: 'white',
                flexShrink: 0,
                [theme.fn.largerThan('sm')]: {
                    width: rem(112),
                    height: rem(112),
                },
                img: {
                    maxWidth: rem(64),
                    [theme.fn.largerThan('sm')]: {
                        maxWidth: rem(73),
                    },
                },
            }) },
            React__default.createElement("img", { alt: "health-tool-icon", src: thumbnail ||
                    ((_b = (_a = allTools.filter((i) => i.template === value)) === null || _a === void 0 ? void 0 : _a[0]) === null || _b === void 0 ? void 0 : _b.icon) ||
                    HEALTH_TOOL_DEFAULT_IMG[value] ||
                    '', loading: "lazy" }))));
};

const HandlerBanner = () => {
    var _a, _b, _c;
    const { t } = useTranslations();
    const { state, Outside } = useContext(SurveyOrPremiumBannerContext);
    return (state === null || state === void 0 ? void 0 : state.action) === BannerAction.ShowTool ? (React__default.createElement(Outside, null, TOOL_BANNERS_PROPS(t)[(_a = state === null || state === void 0 ? void 0 : state.props) === null || _a === void 0 ? void 0 : _a.value] ? (React__default.createElement(ToolBanner, Object.assign({}, TOOL_BANNERS_PROPS(t)[(_b = state === null || state === void 0 ? void 0 : state.props) === null || _b === void 0 ? void 0 : _b.value], { value: (_c = state === null || state === void 0 ? void 0 : state.props) === null || _c === void 0 ? void 0 : _c.value }))) : null)) : (state === null || state === void 0 ? void 0 : state.action) === BannerAction.ShowOptionBanner ? (React__default.createElement(Outside, null,
        React__default.createElement(BannerWithOptions, Object.assign({}, state === null || state === void 0 ? void 0 : state.props)))) : null;
};

const SideBannerModal = (_a) => {
    var { isMobile, children, desktopBanner = CommonGAssets.getAssetPath('friso/onboarding-banner.jpg'), mobileBanner = CommonGAssets.getAssetPath('friso/onboarding-banner-mobile.jpg'), modalRatio = {
        width: 937,
        height: 536,
    }, mobileBannerRatio = {
        width: 750,
        height: 480,
    }, desktopBannerRatio = {
        width: 420,
        height: 536,
    }, closeProps } = _a, modalProps = __rest(_a, ["isMobile", "children", "desktopBanner", "mobileBanner", "modalRatio", "mobileBannerRatio", "desktopBannerRatio", "closeProps"]);
    const { width: viewportWidth, height: viewportHeight } = useViewportSize();
    const curBannerHeight = (viewportWidth * mobileBannerRatio.height) / mobileBannerRatio.width;
    const minHeightNha = (viewportHeight <= 667 ? 190 : 265) + curBannerHeight + 74;
    const [isFullScreen, setIsFullScreen] = useState(false);
    return (React__default.createElement(Modal, Object.assign({ styles: (theme) => ({
            header: {
                display: 'none',
            },
            content: {
                flex: 'auto',
                background: 'transparent',
                [theme.fn.smallerThan('sm')]: {
                    maxHeight: '100%',
                    height: '100%',
                    position: 'relative',
                    borderRadius: 0,
                },
                [theme.fn.largerThan('sm')]: {
                    maxWidth: rem(modalRatio.width),
                    width: '100%',
                    height: '100%',
                    maxHeight: rem(modalRatio.height),
                    boxShadow: 'none',
                },
            },
            body: {
                padding: 0,
                width: '100%',
                height: '100%',
                [theme.fn.largerThan('sm')]: {
                    display: 'flex',
                    alignItems: 'center',
                },
            },
            inner: {
                padding: 0,
                [theme.fn.smallerThan('sm')]: {
                    display: 'flex',
                    alignItems: 'flex-end',
                },
            },
        }) }, modalProps), isMobile ? (React__default.createElement(Box, { sx: {
            position: 'relative',
            width: '100%',
            height: '100%',
        }, onTouchStart: () => setIsFullScreen(true) },
        React__default.createElement(Box, { className: "mobile-template", sx: {
                position: 'absolute',
                height: `${(isFullScreen ? 1 : minHeightNha / viewportHeight) * 100}%`,
                left: 0,
                bottom: 0,
                right: 0,
                transition: 'height 0.4s ease',
            } },
            React__default.createElement(Box, { className: "mobile-template-wrapper", sx: {
                    height: '100%',
                    backgroundColor: 'white',
                    borderTopLeftRadius: isFullScreen ? 0 : rem(12),
                    borderTopRightRadius: isFullScreen ? 0 : rem(12),
                } },
                React__default.createElement(Box, { sx: {
                        // height: 'calc(100% - 74px)',
                        height: '100%',
                        background: `url(${mobileBanner})`,
                        backgroundSize: 'contain',
                        backgroundRepeat: 'no-repeat',
                        backgroundPosition: 'top center',
                        overflowY: 'auto',
                        borderRadius: 'inherit',
                    } },
                    isVideo(mobileBanner) && (React__default.createElement("video", { loop: true, muted: true, autoPlay: true, style: {
                            width: '100%',
                            position: 'absolute',
                            top: 0,
                            left: 0,
                        } },
                        React__default.createElement("source", { src: mobileBanner }))),
                    React__default.createElement(Button, Object.assign({ variant: "white", leftIcon: React__default.createElement(Close, null), sx: {
                            position: 'absolute',
                            right: 0,
                            top: 0,
                            zIndex: 1,
                            padding: rem(10),
                            // backgroundColor: 'transparent',
                        } }, closeProps, { onClick: () => modalProps === null || modalProps === void 0 ? void 0 : modalProps.onClose() })),
                    React__default.createElement(AspectRatio, { ratio: (mobileBannerRatio === null || mobileBannerRatio === void 0 ? void 0 : mobileBannerRatio.width) / (mobileBannerRatio === null || mobileBannerRatio === void 0 ? void 0 : mobileBannerRatio.height), w: "100%" }),
                    React__default.createElement(Box, { className: "inner", sx: {
                            padding: `${rem(28)} ${rem(16)} ${rem(16)}`,
                            background: 'white',
                            position: 'relative',
                        } }, children)))))) : (React__default.createElement(AspectRatio, { className: "desktop-template", ratio: modalRatio.width / modalRatio.height, w: "100%", sx: {
            position: 'relative',
            '& > div': {
                justifyContent: 'flex-end',
            },
        } },
        React__default.createElement(Box, { sx: {
                width: '100%',
                height: '100%',
                justifyContent: 'flex-end',
                alignItems: 'stretch',
                borderRadius: rem(8),
                background: 'white',
                boxShadow: '0 0.0625rem 0.1875rem rgba(0, 0, 0, 0.05), rgba(0, 0, 0, 0.05) 0 2.25rem 1.75rem -0.4375rem, rgba(0, 0, 0, 0.04) 0 1.0625rem 1.0625rem -0.4375rem',
            } },
            isVideo(desktopBanner) ? (React__default.createElement("video", { loop: true, muted: true, autoPlay: true, style: {
                    borderTopLeftRadius: rem(8),
                    borderBottomLeftRadius: rem(8),
                    height: '100%',
                    display: 'block',
                } },
                React__default.createElement("source", { src: desktopBanner }))) : (React__default.createElement("img", { alt: "", src: desktopBanner, loading: "lazy", style: {
                    borderTopLeftRadius: rem(8),
                    borderBottomLeftRadius: rem(8),
                    height: '100%',
                    display: 'block',
                } })),
            React__default.createElement(Box, { sx: {
                    position: 'relative',
                    height: '100%',
                    width: `${((modalRatio.width - desktopBannerRatio.width) /
                        modalRatio.width) *
                        100}%`,
                } },
                React__default.createElement(Button, Object.assign({ variant: "white", leftIcon: React__default.createElement(Close, null) }, closeProps, { onClick: () => modalProps === null || modalProps === void 0 ? void 0 : modalProps.onClose(), sx: {
                        position: 'absolute',
                        right: 0,
                        top: 0,
                        backgroundColor: 'transparent',
                    } })),
                React__default.createElement(Box, { className: "side-banner-modal-container", sx: {
                        height: '100%',
                        padding: `${rem(40)} ${rem(24)} 0`,
                    } }, children)))))));
};

const PATHS = {
    UPDATE_SUBSCRIPTION: 'user/subscription',
};

const PremiumNewsletterModalContext = createContext({});

const _NormalTopic = (_a) => {
    var { value, name } = _a, rest = __rest(_a, ["value", "name"]);
    return (React__default.createElement(ChipButton, Object.assign({ value: value, withIcon: true }, rest, { buttonProps: {
            styles: () => ({
                leftIcon: {
                    marginRight: rem(6),
                },
                root: {
                    paddingLeft: rem(10),
                    paddingRight: rem(10),
                },
            }),
        } }), name));
};

const TopicSection = ({ topicsGroup, onTopicChange, isBlock = false, selectedTopics = [], inputProps, labelProps, maxSelect = 5, hasScroll, readonly, }) => {
    const { action: { pushNotifications }, } = useContext(TogetherComponentGlobalContext);
    const topics = flatten(topicsGroup.map((i) => i.topics || []));
    const { t } = useTranslations();
    const [value, setValue] = useState([]);
    useEffect(() => {
        setValue(selectedTopics);
    }, [selectedTopics.length]);
    useEffect(() => {
        onTopicChange === null || onTopicChange === void 0 ? void 0 : onTopicChange(value);
    }, [value]);
    const onValueChange = (v) => {
        if (v.length > 5) {
            pushNotifications({
                type: 'danger',
                title: t('pnTopicSection.maxSelectError.title', {
                    maxSelect,
                }),
                message: t('pnTopicSection.maxSelectError.desc'),
            });
            return;
        }
        else {
            !readonly &&
                setValue(() => {
                    return topics.filter((topicObj) => v.some((tValue) => topicObj.catId === tValue));
                });
        }
    };
    return (React__default.createElement(Stack, { spacing: 12 }, topicsGroup.map((i, idx) => (React__default.createElement(Stack, { key: String(idx), spacing: 12 },
        i.label && (React__default.createElement(Text, Object.assign({ size: "s5", color: "gray.4", weight: "semiBold" }, labelProps), i.label)),
        hasScroll ? (React__default.createElement(ScrollArea, { w: "100%", offsetScrollbars: true, scrollbarSize: 4, p: 16, m: -16, styles: {
                viewport: {
                    margin: -16,
                    padding: 16,
                },
            } },
            React__default.createElement(Box, { w: 800 },
                React__default.createElement(Chip.Group, Object.assign({ value: value.map((v) => v.catId), multiple: true }, inputProps, { onChange: onValueChange }),
                    React__default.createElement(Flex, { gap: 8, wrap: "wrap" }, i.topics.map((v) => (React__default.createElement(_NormalTopic, Object.assign({ key: v.catId, value: v.catId, name: v.localName, isBlock: isBlock }, i.tracking))))))))) : (React__default.createElement(Chip.Group, Object.assign({ value: value.map((v) => v.catId), multiple: true }, inputProps, { onChange: onValueChange }),
            React__default.createElement(Flex, { gap: 8, wrap: "wrap" }, i.topics.map((v) => v.catId ? (React__default.createElement(_NormalTopic, Object.assign({ key: v.catId, value: v.catId, name: v.localName, isBlock: isBlock }, i.tracking))) : React__default.isValidElement(v.component) ? (v.component) : null)))))))));
};

const Layout = (_a) => {
    var { heading, children, stickyActions } = _a, scrollAreaProps = __rest(_a, ["heading", "children", "stickyActions"]);
    const { isMobile } = useContext(PremiumNewsletterModalContext);
    const content = (React__default.createElement(Stack, { spacing: rem(24), sx: { height: '100%' } },
        React__default.createElement(Heading, { tag: "h4", style: {
                textAlign: 'center',
            } }, heading),
        React__default.createElement(Box, null, children)));
    return (React__default.createElement(Box, { sx: (theme) => ({
            [theme.fn.largerThan('sm')]: {
                position: 'relative',
                height: '100%',
            },
        }) },
        isMobile ? (content) : (React__default.createElement(ScrollArea, Object.assign({ className: "layout-body", h: stickyActions ? 'calc(100% - 90px)' : '100%' }, scrollAreaProps), content)),
        stickyActions && (React__default.createElement(Flex, { gap: rem(8), sx: (theme) => ({
                position: 'absolute',
                left: 0,
                right: 0,
                bottom: 0,
                padding: rem(16),
                button: {
                    flexGrow: 1,
                },
                justifyContent: 'center',
                [theme.fn.largerThan('sm')]: {
                    padding: `${rem(24)} 0`,
                },
            }) }, stickyActions))));
};

const MainForm = () => {
    const { t, locale } = useTranslations();
    const { data: { userInfo }, action: { pushNotifications }, } = useContext(TogetherComponentGlobalContext);
    const isLoggedIn = userInfo === null || userInfo === void 0 ? void 0 : userInfo.id;
    const { currentUrl, isMobile, pnSuggestCategory = [], nextStep, formValues, setFormValues, onSubmit: _onSubmit, submitLoading, selectCategory, setCategoryLibs, setSelectCategory, maxSelectCategory, } = useContext(PremiumNewsletterModalContext);
    const pnSuggestCategoryIds = pnSuggestCategory.map((i) => i.catId);
    const form = useForm({
        validate: {
            name: isNotEmpty(t('healthToolPNModal.mainForm.requireName')),
        },
        initialValues: Object.assign(Object.assign({}, formValues), { fitnessTopics: pnSuggestCategoryIds }),
    });
    const [fitnessTopics, setFitnessTopics] = useState([]);
    const [interestedTopics, setInterestedTopics] = useState([]);
    useEffect(() => {
        (() => __awaiter(void 0, void 0, void 0, function* () {
            var _a;
            try {
                const interestedRes = yield callApiWithAuth(getPremiumApiPath(PATHS$1.GET_SUBSCRIPTION_CATEGORIES, {
                    _locale: locale,
                }), 'get');
                const interestedList = (((_a = interestedRes === null || interestedRes === void 0 ? void 0 : interestedRes.data) === null || _a === void 0 ? void 0 : _a.subscription) || []).filter((i) => !pnSuggestCategoryIds.includes(i.catId));
                setFitnessTopics(pnSuggestCategory);
                setInterestedTopics(interestedList);
                setCategoryLibs([...pnSuggestCategory, ...interestedList]);
            }
            catch (err) {
                console.log(err);
            }
        }))();
    }, []);
    useEffect(() => {
        isLoggedIn && form.setFieldValue('name', (userInfo === null || userInfo === void 0 ? void 0 : userInfo.name) || '');
    }, [isLoggedIn]);
    const onMore = () => {
        if (form.getInputProps('name').value !== '') {
            setFormValues(form.getTransformedValues());
            nextStep();
        }
        else {
            form.validateField('name');
        }
    };
    const onSubmit = (formValues) => {
        if (selectCategory.length === 0) {
            pushNotifications({
                type: 'danger',
                title: t('newsletter.error.minTitle'),
                message: t('newsletter.error.minCotennt'),
            });
            return false;
        }
        setFormValues(formValues);
        _onSubmit === null || _onSubmit === void 0 ? void 0 : _onSubmit(formValues.name);
    };
    const MoreButton = useMemo(() => (React__default.createElement(Button, { variant: "tertiary", dataEventCategory: "Newsletter", dataEventAction: "More Category Click", dataEventLabel: currentUrl, leftIcon: React__default.createElement(Plus, { size: 16, color: 'currentColor' }), onClick: onMore, styles: (theme) => ({
            root: {
                borderRadius: rem(6),
                padding: '2px 15px',
                height: rem(40),
            },
            label: {
                fontSize: rem(14),
                fontWeight: 400,
                [theme.fn.smallerThan('sm')]: {
                    fontSize: rem(12),
                    lineHeight: rem(16),
                    height: rem(40),
                },
            },
            leftIcon: {
                marginRight: '5px',
            },
        }) },
        React__default.createElement(Text, { size: isMobile ? 'p3' : 'p4' }, t('home.seeMore')))), [form]);
    useEffect(() => {
        form.setFieldValue('fitnessTopics', selectCategory.map((i) => i.catId));
    }, [selectCategory]);
    return (React__default.createElement("form", { style: { height: '100%' }, onSubmit: form.onSubmit(onSubmit) },
        React__default.createElement(Layout, { heading: t('healthToolPNModal.heading'), stickyActions: React__default.createElement(React__default.Fragment, null,
                React__default.createElement(Button, { fullWidth: true, type: "submit", dataEventCategory: "Newsletter", dataEventAction: "Register Click", dataEventLabel: currentUrl, loading: submitLoading, sx: { maxWidth: rem(240) } }, t('healthToolPNModal.register'))) },
            React__default.createElement(Stack, { spacing: rem(16) },
                React__default.createElement(Input, Object.assign({ label: t('newsletter.welcome.description') }, form.getInputProps('name'))),
                React__default.createElement(TopicSection, { topicsGroup: [
                        ...(pnSuggestCategory.length === 0 &&
                            interestedTopics.length === 0
                            ? [
                                {
                                    topics: [
                                        {
                                            component: MoreButton,
                                        },
                                    ],
                                },
                            ]
                            : []),
                        ...(pnSuggestCategory.length > 0
                            ? [
                                {
                                    label: t('healthToolPNModal.mainForm.tailorTopicsHeading'),
                                    topics: [
                                        ...pnSuggestCategory,
                                        ...(interestedTopics.length === 0
                                            ? [
                                                {
                                                    component: MoreButton,
                                                },
                                            ]
                                            : []),
                                    ],
                                },
                            ]
                            : []),
                        ...(interestedTopics.length > 0
                            ? [
                                {
                                    label: t('healthToolPNModal.findMore.chooseFav'),
                                    topics: [
                                        ...interestedTopics,
                                        ...(interestedTopics.length > 0
                                            ? [
                                                {
                                                    component: MoreButton,
                                                },
                                            ]
                                            : []),
                                    ],
                                },
                            ]
                            : []),
                    ], selectedTopics: [...fitnessTopics], labelProps: {
                        size: isMobile ? 'p3' : 'p4',
                        color: 'gray.6',
                    }, onTopicChange: setSelectCategory, maxSelect: maxSelectCategory })))));
};

const _SuggestedTopic = forwardRef(function SuggestedTopic(_a, ref) {
    var { label } = _a, others = __rest(_a, ["label"]);
    return (React__default.createElement("div", Object.assign({ ref: ref }, others),
        React__default.createElement(Group, { noWrap: true },
            React__default.createElement("svg", { width: "18", height: "18", viewBox: "0 0 18 18", fill: "none" },
                React__default.createElement("path", { fillRule: "evenodd", clipRule: "evenodd", d: "M2.97887 8.15493C2.97887 5.29627 5.29627 2.97887 8.15493 2.97887C11.0136 2.97887 13.331 5.29627 13.331 8.15493C13.331 11.0136 11.0136 13.331 8.15493 13.331C5.29627 13.331 2.97887 11.0136 2.97887 8.15493ZM8.15493 1.5C4.47951 1.5 1.5 4.47951 1.5 8.15493C1.5 11.8303 4.47951 14.8099 8.15493 14.8099C9.72615 14.8099 11.1702 14.2653 12.3086 13.3547L15.2376 16.2837C15.5264 16.5725 15.9946 16.5725 16.2833 16.2837C16.5721 15.9949 16.5721 15.5267 16.2833 15.238L13.3544 12.3091C14.2652 11.1705 14.8099 9.72634 14.8099 8.15493C14.8099 4.47951 11.8303 1.5 8.15493 1.5Z", fill: "#8C8C8C" })),
            React__default.createElement(Text, { size: "p3" }, label))));
});

const _Topic = forwardRef(function Baby(_a, ref) {
    var { label } = _a, others = __rest(_a, ["label"]);
    return (React__default.createElement("div", Object.assign({ ref: ref }, others),
        React__default.createElement(Text, { size: "p3" }, label)));
});

const HistorySection = ({ history, onDelete }) => {
    return (React__default.createElement(Flex, { wrap: 'wrap', gap: 8 }, uniqBy(history, 'catId').map((h) => (React__default.createElement(Badge, { key: h.catId, rightSection: React__default.createElement("svg", { width: "18", height: "18", viewBox: "0 0 18 18", fill: "none", onClick: () => onDelete === null || onDelete === void 0 ? void 0 : onDelete(h) },
            React__default.createElement("path", { fillRule: "evenodd", clipRule: "evenodd", d: "M1.5 9C1.5 4.8525 4.8525 1.5 9 1.5C13.1475 1.5 16.5 4.8525 16.5 9C16.5 13.1475 13.1475 16.5 9 16.5C4.8525 16.5 1.5 13.1475 1.5 9ZM11.1677 12.2248C11.4602 12.5173 11.9327 12.5173 12.2252 12.2248C12.5101 11.9323 12.5101 11.4523 12.2252 11.1673L10.0577 8.99979L12.2252 6.83229C12.5177 6.53979 12.5177 6.0673 12.2252 5.7748C11.9327 5.4823 11.4602 5.4823 11.1677 5.7748L9.00015 7.9423L6.83265 5.7748C6.54015 5.4823 6.06765 5.4823 5.77515 5.7748C5.63471 5.91492 5.55579 6.10516 5.55579 6.30354C5.55579 6.50193 5.63471 6.69217 5.77515 6.83229L7.94265 8.99979L5.77515 11.1673C5.63471 11.3074 5.55579 11.4977 5.55579 11.696C5.55579 11.8944 5.63471 12.0847 5.77515 12.2248C6.06765 12.5173 6.54015 12.5173 6.83265 12.2248L9.00015 10.0573L11.1677 12.2248Z", fill: "#8C8C8C" })), styles: {
            root: {
                height: 32,
                background: '#ffffff',
                padding: '5px 12px',
                border: `1px solid ${themeColors.neutral[4]}`,
                borderRadius: 32,
                textTransform: 'unset',
            },
            rightSection: {
                height: 18,
                cursor: 'pointer',
            },
        } },
        React__default.createElement(Text, { size: "p4" }, h.localName))))));
};

const RecentlyViewedSection = ({ topics, onTopicChange, isBlock = false, selectedTopics, labelProps, maxSelect = 5, }) => {
    const { action: { pushNotifications }, } = useContext(TogetherComponentGlobalContext);
    const [value, setValue] = useState([]);
    const { t } = useTranslations();
    useEffect(() => {
        setValue(selectedTopics);
    }, [selectedTopics.length]);
    useEffect(() => {
        onTopicChange(value);
    }, [value]);
    const onValueChange = (v) => {
        if (isBlock && value.length < v.length) {
            pushNotifications({
                type: 'danger',
                title: t('pnTopicSection.maxSelectError.title', {
                    maxSelect,
                }),
                message: t('pnTopicSection.maxSelectError.desc'),
            });
            return;
        }
        else {
            setValue(() => {
                return topics.filter((topicObj) => v.some((tValue) => topicObj.catId === tValue));
            });
        }
    };
    if (!topics || topics.length === 0)
        return null;
    return (React__default.createElement(Stack, { spacing: 12, px: 16, mx: -16 },
        React__default.createElement(Text, Object.assign({ size: "s5", color: "gray.4", weight: "semiBold" }, labelProps), t('pnTopicSection.recentView')),
        React__default.createElement(Chip.Group, { value: value.map((v) => v.catId), onChange: onValueChange, multiple: true },
            React__default.createElement(Flex, { gap: 8, wrap: 'wrap' }, topics.map((v, i) => (React__default.createElement(_NormalTopic, { key: i, value: v.catId, name: v.localName, isBlock: isBlock })))))));
};

const _TopicSlide = (_a) => {
    var { topic, active, onClick } = _a, rest = __rest(_a, ["topic", "active", "onClick"]);
    return (React__default.createElement(Box, Object.assign({ sx: (theme) => ({
            position: 'relative',
            cursor: 'pointer',
            padding: 2,
            borderRadius: 8,
            boxShadow: '0px 4px 8px rgba(0, 0, 0, 0.04), 0px 0px 2px rgba(0, 0, 0, 0.06), 0px 0px 1px rgba(0, 0, 0, 0.04)',
            minHeight: rem(130),
            [theme.fn.largerThan('sm')]: {
                minHeight: rem(138),
            },
        }), onClick: () => onClick(topic, active) }, rest),
        active && (React__default.createElement(Box, { id: "test", sx: {
                position: 'absolute',
                top: 2,
                right: 2,
                width: 20,
                height: 20,
                zIndex: 1,
            } },
            React__default.createElement("svg", { id: "test", width: "20", height: "20", viewBox: "0 0 20 20", fill: "none" },
                React__default.createElement("path", { fillRule: "evenodd", clipRule: "evenodd", d: "M1.66699 9.99984C1.66699 5.39984 5.40033 1.6665 10.0003 1.6665C14.6003 1.6665 18.3337 5.39984 18.3337 9.99984C18.3337 14.5998 14.6003 18.3332 10.0003 18.3332C5.40033 18.3332 1.66699 14.5998 1.66699 9.99984ZM4.75066 10.5827L7.74232 13.5744C8.06732 13.8994 8.60066 13.8994 8.91732 13.5744L15.2423 7.2494C15.5673 6.9244 15.5673 6.3994 15.2423 6.0744C14.9173 5.7494 14.3923 5.7494 14.0673 6.0744L8.33399 11.8077L5.92566 9.40773C5.60066 9.08273 5.07566 9.08273 4.75066 9.40773C4.59461 9.56342 4.50692 9.7748 4.50692 9.99523C4.50692 10.2157 4.59461 10.427 4.75066 10.5827Z", fill: "#2D87F3" }),
                React__default.createElement("path", { d: "M7.74224 13.5772L4.75057 10.5856C4.59453 10.4299 4.50684 10.2185 4.50684 9.99808C4.50684 9.77765 4.59453 9.56627 4.75057 9.41058C5.07557 9.08558 5.60057 9.08558 5.92557 9.41058L8.33391 11.8106L14.0672 6.07725C14.3922 5.75225 14.9172 5.75225 15.2422 6.07725C15.5672 6.40225 15.5672 6.92725 15.2422 7.25225L8.91724 13.5772C8.60057 13.9022 8.06724 13.9022 7.74224 13.5772Z", fill: "white" })))),
        React__default.createElement(Box, { sx: { borderRadius: '8px' } },
            React__default.createElement(AspectRatio$1, { ratio: 3 / 2, mb: 10, sx: (theme) => ({
                    background: theme.colors.neutral[0],
                }) },
                React__default.createElement(Box, null,
                    React__default.createElement("img", { src: topic.guid || '', alt: "cat", loading: "lazy", style: {
                            maxHeight: '63px',
                        } })))),
        React__default.createElement(Text, { size: "p4", ta: "center", px: 6, sx: {
                display: '-webkit-box',
                '-webkit-line-clamp': '2',
                '-webkit-box-orient': 'vertical',
                overflow: 'hidden',
            } }, topic.localName || '')));
};

const TrendingCarousel = ({ topics, selectedTopics = [], onTopicChange, isBlock = false, labelProps, pushNotifications, maxSelect = 5, }) => {
    const { t } = useTranslations();
    const [carouselTopics, setCarouselTopics] = useState([]);
    const onSelect = (topic, status) => {
        if (status) {
            setCarouselTopics((pre) => pre.filter((t) => t.catId !== topic.catId));
        }
        else {
            if (isBlock) {
                pushNotifications({
                    type: 'danger',
                    title: t('pnTopicSection.maxSelectError.title', {
                        maxSelect,
                    }),
                    message: t('pnTopicSection.maxSelectError.desc'),
                });
                return;
            }
            setCarouselTopics((pre) => [...pre, topic]);
        }
    };
    useEffect(() => {
        setCarouselTopics(selectedTopics);
    }, [selectedTopics.length]);
    useEffect(() => {
        onTopicChange(carouselTopics);
    }, [carouselTopics]);
    const [isDragging, setIsDragging] = useState(false);
    const [startX, setStartX] = useState(0);
    const [scrollLeft, setScrollLeft] = useState(0);
    const containerRef = useRef(null);
    const handleMouseDown = (e) => {
        e.preventDefault();
        if (!containerRef.current)
            return;
        setIsDragging(true);
        setStartX(e.pageX - containerRef.current.offsetLeft);
        setScrollLeft(containerRef.current.scrollLeft);
    };
    const handleMouseUp = () => {
        setIsDragging(false);
    };
    const handleMouseMove = (e) => {
        e.preventDefault();
        if (!isDragging || !containerRef.current)
            return;
        const x = e.pageX - containerRef.current.offsetLeft;
        const walk = (x - startX) * 2; // adjust scroll speed
        containerRef.current.scrollLeft = scrollLeft - walk;
    };
    return (React__default.createElement(Stack, { spacing: 10 },
        React__default.createElement(Flex, { justify: 'space-between', align: 'center', w: "100%" },
            React__default.createElement(Text, Object.assign({ size: "s5", color: "gray.4", weight: "semiBold", span: true }, labelProps), t('pnTopicSection.trending'))),
        React__default.createElement(Box, null,
            React__default.createElement(ScrollArea, { type: "always", w: "100%", offsetScrollbars: true, scrollbarSize: 4, px: 4, viewportRef: containerRef, viewportProps: {
                    onMouseDown: handleMouseDown,
                    onMouseUp: handleMouseUp,
                    onMouseLeave: handleMouseUp,
                    onMouseMove: handleMouseMove,
                }, styles: {
                    viewport: {
                        paddingBottom: 16,
                    },
                } },
                React__default.createElement(Box, { w: { base: 112 * topics.length + 8 * (topics.length - 1) + 10 } },
                    React__default.createElement(Flex, { gap: 8 }, topics.map((topic, index) => (React__default.createElement(_TopicSlide, { key: index, topic: topic, onClick: onSelect, active: carouselTopics.some((t) => t.catId === topic.catId), w: { base: 112 } })))))))));
};

const PremiumTopicSelect = (_a) => {
    var { isLoggedIn, maxSelect = 5, values: _values = [], labelProps, onChange } = _a, rest = __rest(_a, ["isLoggedIn", "maxSelect", "values", "labelProps", "onChange"]);
    const { action: { pushNotifications }, } = useContext(TogetherComponentGlobalContext);
    const [searchValue, onSearchChange] = useState('');
    const { t, locale } = useTranslations();
    const ref = useRef(null);
    const [history, setHistory] = useState([]);
    const [carouselTopics, setCarouselTopics] = useState([]);
    const [recentlyViewedTopics, setRecentlyViewedTopics] = useState([]);
    const [interestedTopics, setInterestedTopics] = useState([]);
    const [newsletterCategory, setNewsletterCategory] = useState(null);
    const [options, setOptions] = useState([]);
    useEffect(() => {
        (() => __awaiter(void 0, void 0, void 0, function* () {
            var _a, _b;
            const response = yield callApiWithAuth(getPremiumApiPath(PATHS$1.GET_NEWSLETTER_CATEGORIES, { _locale: locale }), 'get');
            const interested = ((_a = response === null || response === void 0 ? void 0 : response.data) === null || _a === void 0 ? void 0 : _a.interested) || [];
            const trending = ((_b = response === null || response === void 0 ? void 0 : response.data) === null || _b === void 0 ? void 0 : _b.trending) || [];
            const uniqueTopics = uniqBy([...interested, ...trending], 'catId');
            const _options = uniqueTopics.map((topic) => (Object.assign(Object.assign({}, topic), { value: topic.catId || '', label: topic.localName || '' })));
            setOptions(_options || []);
            setNewsletterCategory((response === null || response === void 0 ? void 0 : response.data) || null);
            if (_values.length > 0) {
                const interestedSelectedTopics = interested
                    .filter((i) => _values.includes(i.catId))
                    .map((i) => (Object.assign(Object.assign({}, i), { template: 'interested' })));
                const trendingSelectedTopics = trending
                    .filter((i) => _values.includes(i.catId))
                    .map((i) => (Object.assign(Object.assign({}, i), { template: 'trending' })));
                setInterestedTopics(interestedSelectedTopics);
                setCarouselTopics(trendingSelectedTopics);
            }
        }))();
    }, [isLoggedIn]);
    const onDelete = (category) => {
        const reducers = {
            trending: setCarouselTopics,
            recently: setRecentlyViewedTopics,
            interested: setInterestedTopics,
            default: setHistory,
        };
        const reducer = reducers[category.template] || reducers['default'];
        reducer((pre) => {
            const newHistory = [...pre];
            const position = newHistory.findIndex((t) => t.catId === category.catId);
            newHistory.splice(position, 1);
            return newHistory;
        });
    };
    const uniqueTopic = useMemo(() => uniqBy([
        ...history,
        ...carouselTopics,
        ...interestedTopics,
        ...recentlyViewedTopics,
    ], 'catId'), [history, carouselTopics, interestedTopics, recentlyViewedTopics]);
    const [isBlock, setIsBlock] = useState(false);
    useEffect(() => {
        if (uniqueTopic.length >= maxSelect) {
            setIsBlock(true);
        }
        else {
            setIsBlock(false);
        }
        onChange === null || onChange === void 0 ? void 0 : onChange(uniqueTopic);
    }, [uniqueTopic]);
    const onValueChange = (value) => __awaiter(void 0, void 0, void 0, function* () {
        var _b;
        const reducers = {
            trending: setCarouselTopics,
            recently: setRecentlyViewedTopics,
            interested: setInterestedTopics,
            default: setHistory,
        };
        let key = 'default';
        if (!isBlock) {
            const categoryArrays = [
                { key: 'trending', array: newsletterCategory === null || newsletterCategory === void 0 ? void 0 : newsletterCategory.trending },
                { key: 'recently', array: newsletterCategory === null || newsletterCategory === void 0 ? void 0 : newsletterCategory.recently },
                { key: 'interested', array: newsletterCategory === null || newsletterCategory === void 0 ? void 0 : newsletterCategory.interested },
            ];
            const matchingArray = categoryArrays.find((category) => { var _a; return (_a = category.array) === null || _a === void 0 ? void 0 : _a.some((cat) => cat.catId === value[0]); });
            key = (matchingArray === null || matchingArray === void 0 ? void 0 : matchingArray.key) || 'default';
            reducers[key]((pre) => [
                ...pre,
                ...options.filter((topicObj) => value.some((tValue) => topicObj.catId === tValue)),
            ].map((t) => (Object.assign(Object.assign({}, t), { template: key }))));
            (_b = ref.current) === null || _b === void 0 ? void 0 : _b.blur();
        }
        else {
            pushNotifications({
                type: 'danger',
                title: t('pnTopicSection.maxSelectError.title', {
                    maxSelect,
                }),
                message: t('pnTopicSection.maxSelectError.desc'),
            });
        }
        return null;
    });
    return (React__default.createElement(Stack, Object.assign({ spacing: rem(16) }, rest),
        React__default.createElement(Stack, { spacing: rem(8) },
            React__default.createElement(Text, { size: "p3" }, t('pnTopicSection.maxSelectError.detail', {
                max: maxSelect,
                maxTopic: uniqueTopic.length,
            })),
            React__default.createElement(MultiSelect, { ref: ref, maxSelectedValues: 3, styles: {
                    wrapper: {
                        overflow: 'initial !important',
                    },
                    separator: {
                        padding: 16,
                    },
                    separatorLabel: {
                        fontWeight: 600,
                        fontSize: 12,
                        lineHeight: '18px',
                        textTransform: 'uppercase',
                        color: themeColors.gray[4],
                        '&::after': { display: 'none' },
                    },
                    searchInput: {
                        fontSize: 'inherit',
                    },
                    input: {
                        paddingRight: 16,
                    },
                }, nothingFound: React__default.createElement(Text, { size: "s4", color: "gray.6" }, t('pnTopicSection.notFound')), itemComponent: searchValue === '' ? _SuggestedTopic : _Topic, size: "lg", placeholder: t('pnTopicSection.plsEnterFavTopics'), data: options, onSearchChange: onSearchChange, searchValue: searchValue, icon: React__default.createElement("svg", { width: "24", height: "24", viewBox: "0 0 24 24", fill: "none" },
                    React__default.createElement("path", { fillRule: "evenodd", clipRule: "evenodd", d: "M3.97183 10.8732C3.97183 7.0617 7.0617 3.97183 10.8732 3.97183C14.6848 3.97183 17.7746 7.0617 17.7746 10.8732C17.7746 14.6848 14.6848 17.7746 10.8732 17.7746C7.0617 17.7746 3.97183 14.6848 3.97183 10.8732ZM10.8732 2C5.97268 2 2 5.97268 2 10.8732C2 15.7738 5.97268 19.7465 10.8732 19.7465C12.9682 19.7465 14.8936 19.0205 16.4115 17.8063L20.3168 21.7116C20.7018 22.0966 21.3261 22.0966 21.7111 21.7116C22.0961 21.3266 22.0961 20.7023 21.7111 20.3173L17.8059 16.4121C19.0203 14.894 19.7465 12.9684 19.7465 10.8732C19.7465 5.97268 15.7738 2 10.8732 2Z", fill: "#595959" })), rightSection: React__default.createElement(React__default.Fragment, null), zIndex: 500, searchable: true, withinPortal: true, onChange: (val) => onValueChange(val), value: [] }),
            uniqueTopic && uniqueTopic.length > 0 && (React__default.createElement(HistorySection, { history: uniqueTopic, onDelete: onDelete }))),
        React__default.createElement(Box, { sx: (theme) => ({
                position: 'relative',
                height: rem(175),
                [theme.fn.largerThan('sm')]: {
                    height: rem(190),
                },
            }) },
            React__default.createElement(Box, { sx: {
                    position: 'absolute',
                    top: 0,
                    right: 0,
                    left: 0,
                } },
                React__default.createElement(TrendingCarousel, { topics: ((newsletterCategory === null || newsletterCategory === void 0 ? void 0 : newsletterCategory.trending) || []).map((t) => (Object.assign(Object.assign({}, t), { template: 'trending' }))), selectedTopics: carouselTopics, onTopicChange: setCarouselTopics, isBlock: isBlock, labelProps: labelProps }))),
        React__default.createElement(RecentlyViewedSection, { topics: ((newsletterCategory === null || newsletterCategory === void 0 ? void 0 : newsletterCategory.recently) || []).map((t) => (Object.assign(Object.assign({}, t), { template: 'recently' }))), selectedTopics: recentlyViewedTopics, onTopicChange: setRecentlyViewedTopics, isBlock: isBlock, labelProps: labelProps }),
        React__default.createElement(TopicSection, { labelProps: labelProps, topicsGroup: [
                {
                    label: t('pnTopicSection.ppAlsoInterested'),
                    topics: ((newsletterCategory === null || newsletterCategory === void 0 ? void 0 : newsletterCategory.interested) || []).map((t) => (Object.assign(Object.assign({}, t), { template: 'interested' }))),
                },
            ], selectedTopics: interestedTopics, onTopicChange: setInterestedTopics, isBlock: isBlock })));
};

const MoreTopics = () => {
    const { t } = useTranslations();
    const { action: { pushNotifications }, } = useContext(TogetherComponentGlobalContext);
    const { prevStep, formValues, submitLoading, onSubmit, selectCategory, maxSelectCategory, setSelectCategory, currentUrl, isLoggedIn, } = useContext(PremiumNewsletterModalContext);
    const handleOnSubmit = () => {
        if (selectCategory.length === 0) {
            pushNotifications({
                type: 'danger',
                title: t('newsletter.error.minTitle'),
                message: t('newsletter.error.minCotennt'),
            });
            return false;
        }
        onSubmit === null || onSubmit === void 0 ? void 0 : onSubmit(formValues.name);
    };
    return (React__default.createElement(Layout, { heading: t('newsletter.topic.title'), type: "always", styles: {
            root: {
                paddingRight: rem(25),
            },
        }, stickyActions: React__default.createElement(React__default.Fragment, null,
            React__default.createElement(Button, { fullWidth: true, variant: "secondary", dataEventCategory: "Newsletter", dataEventAction: "Back  Click", dataEventLabel: currentUrl, onClick: prevStep }, t('healthToolPNModal.back')),
            React__default.createElement(Button, { fullWidth: true, type: "submit", dataEventCategory: "Newsletter", dataEventAction: "Next  Click", dataEventLabel: currentUrl, onClick: handleOnSubmit, loading: submitLoading }, t('healthToolPNModal.next'))) },
        React__default.createElement(PremiumTopicSelect, { isLoggedIn: isLoggedIn, maxSelect: maxSelectCategory, values: formValues.fitnessTopics, onChange: setSelectCategory, labelProps: {
                size: 's5',
                sx: {
                    textTransform: 'uppercase',
                },
            } })));
};

const Result = () => {
    const { t } = useTranslations();
    const { close, selectCategory, onRegisterSuccess, currentUrl, finishLabelOnResult, disclaimerText, } = useContext(PremiumNewsletterModalContext);
    useEffect(() => {
        return () => {
            setTimeout(() => {
                onRegisterSuccess === null || onRegisterSuccess === void 0 ? void 0 : onRegisterSuccess();
            }, 400);
        };
    }, []);
    return (React__default.createElement(Layout, { heading: t('healthToolPNModal.heading'), stickyActions: React__default.createElement(Button, { fullWidth: true, sx: { maxWidth: rem(300) }, dataEventCategory: "Newsletter", dataEventAction: "Continue Reading Click", dataEventLabel: currentUrl, onClick: () => {
                close();
            } }, finishLabelOnResult || t('healthToolPNModal.finish')) },
        React__default.createElement(Stack, null,
            React__default.createElement(Flex, { gap: rem(8), sx: (theme) => ({
                    background: theme.colors.green[0],
                    border: `1px solid ${theme.colors.green[1]}`,
                    borderRadius: rem(8),
                    padding: rem(8),
                }) },
                React__default.createElement(Box, null,
                    React__default.createElement("svg", { width: "20", height: "20", viewBox: "0 0 20 20", fill: "none" },
                        React__default.createElement("path", { d: "M9.99984 18.3334C14.6022 18.3334 18.3332 14.6025 18.3332 10.0001C18.3332 5.39771 14.6022 1.66675 9.99984 1.66675C5.39746 1.66675 1.6665 5.39771 1.6665 10.0001C1.6665 14.6025 5.39746 18.3334 9.99984 18.3334Z", fill: "#00B16A" }),
                        React__default.createElement("path", { d: "M9.58558 12.6674C9.22944 12.668 8.87668 12.5983 8.54752 12.4623C8.21835 12.3264 7.91925 12.1268 7.66732 11.8751L6.68587 10.8931C6.55607 10.7587 6.48424 10.5787 6.48587 10.3919C6.48749 10.2051 6.56243 10.0263 6.69455 9.89422C6.82667 9.7621 7.00539 9.68716 7.19222 9.68554C7.37906 9.68391 7.55906 9.75574 7.69345 9.88554L8.67491 10.8675C8.79344 10.986 8.93415 11.08 9.08902 11.1442C9.24389 11.2083 9.40987 11.2413 9.5775 11.2413C9.74513 11.2413 9.91111 11.2083 10.066 11.1442C10.2208 11.08 10.3616 10.986 10.4801 10.8675L16.7033 5.24335C16.8443 5.12184 17.0272 5.06032 17.213 5.07195C17.3987 5.08358 17.5726 5.16744 17.6973 5.30558C17.8221 5.44373 17.8878 5.6252 17.8805 5.81118C17.8731 5.99717 17.7933 6.17291 17.6581 6.30081L11.4592 11.8998C11.2128 12.1448 10.9205 12.3387 10.5989 12.4705C10.2774 12.6022 9.93304 12.6692 9.58558 12.6674Z", fill: "white" }))),
                React__default.createElement(Text, { size: "p3" }, disclaimerText || t('pnModal.disclaimer'))),
            React__default.createElement(Heading, { tag: "h5" }, t('healthToolPNModal.yourPre')),
            selectCategory.length > 0 && (React__default.createElement(TopicSection, { topicsGroup: [{ label: '', topics: selectCategory }], selectedTopics: selectCategory, readonly: true })))));
};

const PremiumNewsletterModal = ({ isMobile, isLoggedIn, pnSuggestCategory = [], acquisitionInfo, currentUrl, opened, close, finishLabelOnResult, onRegisterSuccess, disclaimerText, }) => {
    const { t, locale } = useTranslations();
    const { action: { pushNotifications }, } = useContext(TogetherComponentGlobalContext);
    const desktopBanner = CommonGAssets.getAssetPath('premiumNewsletter/side-banner-desktop.jpg');
    const mobileBanner = CommonGAssets.getAssetPath('premiumNewsletter/side-banner-mobile.jpg');
    const [categoryLibs, setCategoryLibs] = useState([]);
    const [selectCategory, setSelectCategory] = useState([]);
    const [activeStep, setActiveStep] = useState(0);
    const [formValues, setFormValues] = useState({
        name: '',
        fitnessTopics: [],
    });
    const [submitLoading, setSubmitLoading] = useState(false);
    const nextStep = () => setActiveStep((current) => (current < 3 ? current + 1 : current));
    const prevStep = () => setActiveStep((current) => (current > 0 ? current - 1 : current));
    const lastStep = () => setActiveStep(2);
    const handleSubscription = useCallback((name) => __awaiter(void 0, void 0, void 0, function* () {
        try {
            setSubmitLoading(true);
            yield callApiWithAuth(getPremiumApiPath(PATHS$1.POST_SUBSCRIPTION, {
                website_url: getWebsiteUrlApi(locale),
            }), 'post', {
                headers: {
                    'Content-Type': 'application/json',
                },
                method: 'POST',
                data: {
                    ga_client_id: Cookies.get(GA_TOKEN_COOKIE),
                    client_ip: window.clientIP || '',
                    user_info: Object.assign(Object.assign({}, acquisitionInfo.userInfo), { name: name || formValues.name, type_subscription: 1 }),
                    domain: domainLocales[locale || LOCALE.Vietnam],
                    category: selectCategory,
                    perferred: acquisitionInfo.preferredTopics.map(({ id }) => ({
                        id,
                    })),
                },
            });
            setSubmitLoading(false);
            // if (subscripRes?._data?.status === 1) {
            yield callApiWithAuth(getSsoApiPath(PATHS.UPDATE_SUBSCRIPTION), 'post', {
                headers: {
                    'Content-Type': 'application/json',
                },
                method: 'PUT',
                data: {
                    subscription: 1,
                },
            });
            // if (res?.code === 0) {
            // onRegisterSuccess?.()
            lastStep();
            // } else {
            //   pushNotifications({
            //     title: f({ id: 'notification.comment.somethingWrong' }),
            //     message: '',
            //     type: 'danger',
            //   })
            // }
            // } else {
            //   pushNotifications({
            //     title: f({ id: 'notification.comment.somethingWrong' }),
            //     message: '',
            //     type: 'danger',
            //   })
            // }
        }
        catch (err) {
            console.log({ err });
            setSubmitLoading(false);
            pushNotifications({
                title: t('notification.comment.somethingWrong'),
                message: '',
                type: 'danger',
            });
        }
    }), [formValues, selectCategory]);
    useEffect(() => {
        const preloadList = [desktopBanner, mobileBanner];
        preloadList.forEach((image) => {
            const newImage = new Image();
            newImage.src = image;
        });
    }, []);
    return (React__default.createElement(PremiumNewsletterModalContext.Provider, { value: {
            currentUrl,
            isMobile,
            isLoggedIn,
            opened,
            close: close,
            pnSuggestCategory,
            nextStep,
            prevStep,
            lastStep,
            categoryLibs,
            setCategoryLibs,
            selectCategory,
            setSelectCategory,
            formValues,
            setFormValues,
            maxSelectCategory: 5,
            submitLoading,
            onSubmit: handleSubscription,
            onRegisterSuccess,
            finishLabelOnResult,
            disclaimerText,
        } },
        React__default.createElement(SideBannerModal, { isMobile: isMobile, desktopBanner: CommonGAssets.getAssetPath('premiumNewsletter/side-banner-desktop.jpg'), mobileBanner: CommonGAssets.getAssetPath('premiumNewsletter/side-banner-mobile.jpg'), modalRatio: {
                width: 960,
                height: 588,
            }, desktopBannerRatio: {
                width: 384,
                height: 588,
            }, opened: opened, onClose: close, zIndex: 305, closeProps: {
                dataEventCategory: 'Newsletter',
                dataEventAction: 'Close Click',
                dataEventLabel: currentUrl,
            } },
            React__default.createElement(Stepper, { active: activeStep, onStepClick: setActiveStep, styles: {
                    root: {
                        height: '100%',
                    },
                    content: {
                        padding: 0,
                        height: '100%',
                        width: '100%',
                    },
                    steps: {
                        display: 'none',
                    },
                } },
                React__default.createElement(Stepper.Step, null,
                    React__default.createElement(MainForm, null)),
                React__default.createElement(Stepper.Step, null,
                    React__default.createElement(MoreTopics, null)),
                React__default.createElement(Stepper.Step, null,
                    React__default.createElement(Result, null))))));
};

const SurveyBanner = () => {
    const { locale } = useTranslations();
    const { isMobile, isLoggedIn, currentUrl, acquisitionInfo, categoryIds, state, setState, settings, submitHandler, subcribeHealthStatus, showPNModal, setShowPNModal, setIsBack, } = useContext(SurveyOrPremiumBannerContext);
    const [pnSuggestCategory, setPnSuggestCategory] = useState([]);
    const [showModal, setShowModal] = useState(showPNModal);
    useEffect(() => {
        (() => __awaiter(void 0, void 0, void 0, function* () {
            var _a, _b;
            const pnRes = yield callApiWithAuth(getPremiumApiPath(PATHS$1.GET_NEWSLETTER_CATEGORIES, {
                _locale: locale,
            }), 'get');
            const interested = ((_a = pnRes === null || pnRes === void 0 ? void 0 : pnRes.data) === null || _a === void 0 ? void 0 : _a.interested) || [];
            const trending = ((_b = pnRes === null || pnRes === void 0 ? void 0 : pnRes.data) === null || _b === void 0 ? void 0 : _b.trending) || [];
            const allTopics = [...interested, ...trending];
            setPnSuggestCategory(allTopics.filter((i) => categoryIds.includes(Number(i.catId))));
        }))();
    }, []);
    const lastSubcribeHealthStatus = useRef([]);
    useEffect(() => {
        const selectedStep = (subcribeHealthStatus === null || subcribeHealthStatus === void 0 ? void 0 : subcribeHealthStatus.value) || '';
        const splitSelectedStep = selectedStep.split('|').filter(Boolean);
        let selectedStepVerify = selectedStep;
        lastSubcribeHealthStatus.current.push(subcribeHealthStatus);
        if (splitSelectedStep.length > 1) {
            if (lastSubcribeHealthStatus.current[0] !== null) {
                setIsBack(true);
            }
            Object.keys(submitHandler).map((submitKey) => {
                const submitKeyArr = submitKey.split('|');
                if (splitSelectedStep.length === submitKeyArr.length) {
                    let countEqual = 0;
                    splitSelectedStep.map((j) => {
                        if (submitKeyArr.includes(String(j))) {
                            countEqual += 1;
                        }
                    });
                    if (countEqual === splitSelectedStep.length) {
                        selectedStepVerify = submitKey;
                    }
                }
            });
        }
        const stateProps = splitSelectedStep.length > 0
            ? submitHandler[selectedStepVerify]
            : settings;
        setState(stateProps);
    }, [subcribeHealthStatus]);
    useEffect(() => {
        setShowModal(showPNModal);
    }, [showPNModal]);
    return (state === null || state === void 0 ? void 0 : state.action) !== BannerAction.Hide ? (React__default.createElement(React__default.Fragment, null,
        React__default.createElement(HandlerBanner, Object.assign({}, settings.props)),
        React__default.createElement(PremiumNewsletterModal, { acquisitionInfo: acquisitionInfo, isMobile: isMobile, isLoggedIn: isLoggedIn, currentUrl: currentUrl, pnSuggestCategory: pnSuggestCategory, opened: showModal, close: () => {
                var _a;
                setShowModal(false);
                setShowPNModal(false);
                setTimeout(() => {
                    var _a;
                    if ((_a = state.actionParams) === null || _a === void 0 ? void 0 : _a.hideBannerWhenClose) {
                        setState({
                            action: BannerAction.Hide,
                        });
                    }
                }, 400);
                if ((_a = state.actionParams) === null || _a === void 0 ? void 0 : _a.hideBannerWhenClose) {
                    setState({
                        action: BannerAction.Hide,
                    });
                }
            }, onRegisterSuccess: () => setShowModal(false) }))) : null;
};

const SurveyOrPremiumBanner = ({ type, articleId = 0, categoryIds = [], isMarketing, isSurveyType, hasPremiumBanner, currentUrl, isMobile, subcribeHealthStatus, setShouldAcquisitionModalOpen, onValueChange, source = 'discover', Wrapper, }) => {
    const { t } = useTranslations();
    const { data: { userInfo }, } = useContext(TogetherComponentGlobalContext);
    const isLoggedIn = Boolean(userInfo === null || userInfo === void 0 ? void 0 : userInfo.id);
    const [acquisitionInfo, setAcquisitionInfo] = useState(null);
    const [state, setState] = useState();
    const [value, setValue] = useState('');
    const [showPNModal, setShowPNModal] = useState(false);
    const [isBack, setIsBack] = useState(false);
    const surveyType = useMemo(() => MAPPING_CATEGORY_PREMIUM_TYPE[type], []);
    const settings = FLOW(t, currentUrl)[surveyType];
    const submitHandler = settings === null || settings === void 0 ? void 0 : settings.submitHandler;
    const getMappingMultiValue = (value) => {
        let activeKeys = '';
        const valueArr = value.split('|');
        if (valueArr.length === 1)
            return value;
        Object.keys(submitHandler).map((submitKey) => {
            const submitKeyArr = submitKey.split('|');
            if (valueArr.length === submitKeyArr.length) {
                let countEqual = 0;
                valueArr.map((j) => {
                    if (submitKeyArr.includes(String(j))) {
                        countEqual += 1;
                    }
                });
                if (countEqual === valueArr.length) {
                    activeKeys = submitKey;
                }
            }
        });
        return activeKeys;
    };
    const handleClickOption = (value) => {
        const activeKeys = getMappingMultiValue(value);
        if (activeKeys) {
            const i = submitHandler[activeKeys];
            if (i.action === BannerAction.ShowPremiumModal) {
                if (hasPremiumBanner) {
                    setShowPNModal(true);
                    setState(Object.assign(Object.assign({}, state), { actionParams: {
                            hideBannerWhenClose: i.action === BannerAction.ShowPremiumModal,
                        } }));
                }
                else {
                    setState({ action: BannerAction.Hide });
                    onValueChange === null || onValueChange === void 0 ? void 0 : onValueChange(value);
                }
            }
            else {
                setState(i);
                onValueChange === null || onValueChange === void 0 ? void 0 : onValueChange(value);
            }
        }
    };
    const Outside = Wrapper || Box;
    const handleShowPNBannerFlowWhenLogin = () => hasPremiumBanner && (userInfo === null || userInfo === void 0 ? void 0 : userInfo.subscription) !== 1 ? React__default.createElement(PnBannerEle, null) : null;
    const handleShowSurveyBannerFlow = () => {
        const submitValue = submitHandler[(subcribeHealthStatus === null || subcribeHealthStatus === void 0 ? void 0 : subcribeHealthStatus.value) || ''];
        if ((submitValue === null || submitValue === void 0 ? void 0 : submitValue.action) === BannerAction.ShowPremiumModal) {
            return handleShowPNBannerFlowWhenLogin();
        }
        else {
            return React__default.createElement(SurveyBanner, null);
        }
    };
    useEffect(() => {
        if (isLoggedIn) {
            setAcquisitionInfo({
                userInfo,
                preferredTopics: PREFER_TOPICS,
                healthTopics: [],
            });
        }
    }, [isLoggedIn]);
    return (React__default.createElement(SurveyOrPremiumBannerContext.Provider, { value: {
            settings,
            submitHandler,
            type,
            surveyType,
            value,
            setValue,
            isMobile,
            isLoggedIn,
            isMarketing,
            hasPremiumBanner,
            currentUrl,
            acquisitionInfo,
            categoryIds,
            subcribeHealthStatus,
            articleId,
            onValueChange,
            state,
            setState,
            handleClickOption,
            showPNModal,
            setShowPNModal,
            source,
            Outside,
            isBack,
            setIsBack,
            minHeight: 180,
            setShouldAcquisitionModalOpen,
        } }, subcribeHealthStatus !== undefined ? (isLoggedIn ? (isSurveyType && settings ? (handleShowSurveyBannerFlow()) : (handleShowPNBannerFlowWhenLogin())) : hasPremiumBanner ? (React__default.createElement(PnBannerEle, null)) : null) : null));
};

export { MAPPING_CATEGORY_PREMIUM_TYPE as M, SurveyOrPremiumBanner as S, MAPPING_CATEGORY_PREMIUM_API_TYPE as a, SideBannerModal as b };
