<template>
  <div>Test</div>
</template>

<script>
import * as lodash from 'lodash'

import { AccountManager, UserService } from '@nuskin/ns-account'
import webLoyalty from '@nuskin/ns-loyalty-web'
import {
    ConfigService,
    RunConfigService,
    StringService,
    events,
    storage
} from '@nuskin/ns-util'

import NsCheckbox from './common/ns-checkbox'
import NsPopup from './common/ns-popup'

// import i18nSim from '../assets/js/i18n-sim'

const CLOSE_MAPPING = {
    background: events.loyalty.LOYALTY_MODAL_OUTSIDE_CANCEL,
    closeButton: events.loyalty.LOYALTY_MODAL_XCANCEL
}

export default {
    name: 'ns-loyalty-dist-optin',
    components: {
        'ns-checkbox': NsCheckbox,
        NsPopup
    },
    props: {
        eventContext: {
            type: String,
            required: true
        },
        showOnMounted: {
            type: Boolean,
            default: false
        },
        showLearnMoreLink: {
            type: Boolean,
            default: true
        },
        target: {
            type: String,
            default: '_blank'
        }
    },
    data: function() {
        return {
            headLogo: '',
            headName: '',

            agreeTermsAndConditions: false,
            language: '',
            market: '',
            learnMore: '#',
            termsAndConditions: '#',
            content: {}
        }
    },
    methods: {
        close(eventName) {
            if (eventName) {
                events.publish(CLOSE_MAPPING[eventName] || eventName, {
                    context: this.eventContext
                })
            }
            events.publish(events.loyalty.LOYALTY_OPT_IN_CLOSED)

            this.$refs.popup.close()
        },
        open(force) {
            if (force) {
                this.reset()
                this._open_()
            } else {
                webLoyalty.loyaltyCanOptIn().then(canOptIn => {
                    if (canOptIn) {
                        this.reset()
                        this._open_()
                    }
                })
            }
        },
        async _open_() {
            if (!this.headName) {
                if (UserService.isLoggedIn()) {
                    let user = await UserService.getUser()
                    this.headName = user.firstName || ''
                }
            }

            this.$refs.popup.open()
        },
        optIn() {
            webLoyalty.loyaltyOptIn().then(response => {
                events.publish(events.loyalty.LOYALTY_JOIN_NOW, {
                    context: this.eventContext,
                    success: !!response.success
                })

                if (response.success) {
                    events.publish(events.loyalty.LOYALTY_SIGNUP_UPDATE)

                    this.close()
                } else {
                    this.$refs.popup.showFeedback(
                        this.translate('baOptInOptInError'),
                        response.message
                    )
                }
            })
        },
        openTermsAndConditions(ev) {
            let target = ev.target
            if (target.classList.contains('text-link')) {
                ev.preventDefault()

                events.publish(events.loyalty.LOYALTY_TERMS_AND_CONDITIONS, {
                    context: this.eventContext
                })
                window.open(this.termsAndConditions, this.target)
            }
        },
        publishEvent(eventName, payload, ev) {
            events.publish(eventName, { ...payload, context: this.eventContext })

            if (ev) {
                ev.preventDefault()
            }
        },
        reset() {
            this.agreeTermsAndConditions = false

            this.$refs.popup.reset()
        },
        translate(key, data) {
            return key
            // return i18nSim.$t(this.content, key, data)
        }
    },
    created() {
        const marketConfig = ConfigService.getMarketConfig()
        const runConfig = RunConfigService.getRunConfig()

        this.language = runConfig.language
        this.market = runConfig.country

        this.headLogo =
            marketConfig.loyalty.landingPageLogo ||
            '/content/dam/apps/loyalty/global/enJoy_nuskinrewards_white.svg'

        const linkParams = {
            language: this.language,
            market: this.market
        }

        this.learnMore = marketConfig.loyalty.landingPage.replace(
            /\{locale\}/g,
            this.language + '_' + this.market
        )
        // eslint-disable-next-line no-template-curly-in-string
        this.termsAndConditions = lodash.template(
            '/content/dam/apps/loyalty/${language}_${market}/TermsAndConditions.pdf'
        )(linkParams)

        /* eslint-disable */
        StringService.getApplicationStrings('loyalty', {
            baOptInTitle: 'Nu Skin enJoy Rewards',
            baOptInText:
                "EnJoy is a rewards based program based on how you spend. The more you shop, the more rewards you'll discover!",
            baOptInLearnMore: 'Learn More',
            baOptInTermsAndConditions:
                'I have read, understand and agree to the <span class="text-link">Terms and Conditions</span>.',
            baOptInJoinNow: 'Join Now',
            baOptInCancel: 'Cancel',
            baOptInOptInError:
                'Opt-in option is unavailable because an error occurred.'
        }).then(content => {
            this.content = content
        })
        /* eslint-enable */
    },
    destroyed() {
        events.unsubscribe(events.loyalty.LOYALTY_BA_OPTIN_OPEN)
    },
    beforeMount() {
        events.subscribe(events.loyalty.LOYALTY_BA_OPTIN_OPEN, force => {
            this.open(force)
        })
    },
    async mounted() {
        if (this.showOnMounted) {
            let user = await UserService.getUser()
            if (user) {
                let userId = user.id

                let userOptin = storage.getItem(
                    storage.metadata.LOYALTY_SIGNUP_SHOW
                )
                if (userId !== userOptin) {
                    storage.setItem(
                        storage.metadata.LOYALTY_SIGNUP_SHOW,
                        userId
                    )

                    this.open()
                }
            }
        }
    }
}
</script>

<style lang="scss" scoped>
@use "sass:map";
@use "~@nuskin/ns-core-styles/src/scss/colors";
@use "~@nuskin/ns-core-styles/src/scss/global.mixins";

@import '../assets/css/text.mixins.scss';
@import '../assets/css/view-size.mixins';
@import '../assets/css/confirm-reject-button-container';

$color-ash: map.get(colors.$baseColors, ash);
$color-blackhole: map.get(colors.$baseColors, blackhole);
$color-text-link: #6236ff;
$color-black: #000000;
$color-white: #ffffff;

a {
    @include a-link($color-text-link);
}

.tx-em-style-none {
    ::v-deep {
        b,
        em,
        i {
            font-style: normal;
        }
    }
}

.tx-em-bold-600 {
    ::v-deep {
        b,
        em,
        i {
            font-weight: 600;
        }
    }
}

.tx-em-bold-800 {
    ::v-deep {
        b,
        em,
        i {
            font-weight: 800;
        }
    }
}

.ns-opt-in {
    color: $color-blackhole;
    font-family: 'proxima-nova';
}

.c-body {
    .c-description {
        margin: 16px 0 0;
    }

    .c-accept-checkbox {
        margin: 30px 0 0;

        .input-text {
            font-size: 16px;
            font-weight: 600;
            line-height: 1.375em;
        }
    }

    .slot-container {
        overflow: hidden;
    }
}

::v-deep {
    a {
        @include a-link($color-text-link);
    }

    .text-link {
        @include a-link($color-text-link);
    }

    .tx-title-case {
        text-transform: capitalize;
    }
}

.c-heading {
    text-align: inherit;
    margin: 0;
    padding: 0;
    color: $color-blackhole;
    font-size: 18px;
    font-weight: 600;
    line-height: 1.3333em;
}

.c-button-container {
    @include confirm-reject-button-container();

    margin: 30px 0 0;
}
</style>
