<template>
  <ns-popup
    ref="popup"
    class="ns-convert-popup"
    :closable="false"
    :greeting="headName ? translate('convertToLoyalty.greeting', { name: headName }) : ''"
    :head-logo="headLogo"
  >
    <template #pageIntroduction>
      <div class="c-body">
        <h2 class="c-heading title-small-bold">{{ translate('convertToLoyalty.introduction.heading') }}</h2>
        <p class="c-description p-medium tx-em-bold-600 tx-em-style-none">
          <span v-html="translate('convertToLoyalty.introduction.text')"></span>
        </p>
        <ns-checkbox class="c-accept-checkbox" box-color="#6236FF" v-model="agreeTermsAndConditions">
          <template #label>
            <div class="input-text title-small-bold" v-html="translate('convertToLoyalty.introduction.termsAndConditions')" @click="openTermsAndConditions($event)"></div>
          </template>
        </ns-checkbox>
        <div class="c-button-container">
          <button class="primary-solid fluid short bc-accept title-small-bold" :disabled="!agreeTermsAndConditions" @click="accept()">
            <span>{{ translate('convertToLoyalty.introduction.acceptButton') }}</span>
          </button>
          <button class="primary-ghost fluid short bc-cancel title-small-bold" @click="reject()">
            <span>{{ translate('convertToLoyalty.introduction.rejectButton') }}</span>
          </button>
        </div>
      </div>
    </template>
    <template #pageConfirm>
      <div class="c-body">
        <h2 class="c-heading title-small-bold">{{ translate('convertToLoyalty.confirm.heading') }}</h2>
        <p class="c-description p-medium tx-em-bold-600 tx-em-style-none">
          <span v-html="translate('convertToLoyalty.confirm.text')"></span>
        </p>
        <div class="c-button-container">
          <button class="primary-solid fluid short bc-accept title-small-bold" @click="confirmRejection()">
            <span>{{ translate('convertToLoyalty.confirm.confirmButton') }}</span>
          </button>
          <button class="primary-ghost fluid short bc-cancel title-small-bold" @click="goToIntro()">
            <span>{{ translate('convertToLoyalty.confirm.backButton') }}</span>
          </button>
        </div>
      </div>
    </template>
  </ns-popup>
</template>

<script>

import * as lodash from 'lodash'

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

import i18nSim from '../i18n-sim'

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

const ANALYTIC_CONTEXT = 'accepttandc'

export default {
  name: 'NsLoyaltyAcceptTc',
  components: {
    'ns-checkbox': NsCheckbox,
    NsPopup
  },
  props: {
    target: {
      type: String,
      default: '_blank'
    }
  },
  data: function () {
    return {
      headLogo: '',
      headName: '',

      language: '',
      market: '',
      points: 0,
      agreeTermsAndConditions: false,
      termsAndConditions: '#',
      content: {}
    }
  },
  methods: {
    async accept () {
      await webLoyalty.setUserViewedTandC()

      this.$refs.popup.close()
    },
    async confirmRejection () {
      let response = await webLoyalty.loyaltyOptOut()

      events.publish(events.loyalty.LOYALTY_OPTOUT_CONFIRM, { context: ANALYTIC_CONTEXT, success: !!response.success })

      if (response.success === true) {
        response = await webLoyalty.setUserViewedTandC()
      }

      this.$refs.popup.close()
    },
    goToConfirm () {
      this.$refs.popup.showView('pageConfirm')
    },
    goToIntro () {
      this.$refs.popup.showView('pageIntroduction')
    },
    async open (force) {
      if (force) {
        this.reset(true)
        this.$refs.popup.open()
      } else if (UserService.isLoggedIn()) {
        const user = await UserService.getUser()
        this.headName = user.firstName || ''

        let tcData = await webLoyalty.getRewardsPoints()
        if (tcData && tcData.user && !tcData.user.adrConversionOptInViewedStatus) {
            this.points = tcData.wallet.available

            this.$refs.popup.open()
        }
      }
    },
    openTermsAndConditions (ev) {
      let target = ev.target.closest('.text-link')
      if (target) {
        ev.preventDefault()

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

      if (ev) {
        ev.preventDefault()
      }
    },
    reject () {
      if (this.points > 0) {
        this.goToConfirm()
      } else {
        this.confirmRejection()
      }
    },
    reset (form) {
      if (form) {
        this.agreeTermsAndConditions = false
      }

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

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

    const linkParams = {
      'locale': this.language + '_' + this.market,
      'language': this.language,
      'market': this.market
    }

    this.headLogo = marketConfig.loyalty.landingPageLogo || '/content/dam/apps/loyalty/global/enJoy_nuskinrewards_white.svg'
    // eslint-disable-next-line no-template-curly-in-string
    this.termsAndConditions = lodash.template('/content/dam/apps/loyalty/${language}_${market}/TermsAndConditions.pdf')(linkParams)

    StringService.getApplicationStrings('loyalty', {
      'convertToLoyalty.greeting': 'Hey <span class="tx-title-case">{name}</span>, are you ready to enjoy?',
      'convertToLoyalty.introduction.heading': 'We have great news!',
      'convertToLoyalty.introduction.error': 'Opt-in process did not complete because of an error. Please try again later.',
      'convertToLoyalty.introduction.text': 'We are introducing our exciting new Loyalty Program <em>Nu Skin enJoy Rewards!</em> Once opted in, your remaining ADR points will be converted into <em>enJoy credits</em> to redeem while shopping!',
      'convertToLoyalty.introduction.termsAndConditions': 'I have read, understand and agree to the <span class="text-link">Terms and Conditions</span>.',
      'convertToLoyalty.introduction.acceptButton': 'Join Now',
      'convertToLoyalty.introduction.rejectButton': 'No Thanks',
      'convertToLoyalty.confirm.heading': 'Opt out of Nu Skin enJoy Rewards',
      'convertToLoyalty.confirm.text': 'You have <em>unspent ADR points</em> that can be converted to credits. By selecting confirm you <em>will lose these credits</em>. Do you still wish to proceed?',
      'convertToLoyalty.confirm.confirmButton': 'Confirm',
      'convertToLoyalty.confirm.backButton': 'Back'
    }).then((content) => {
      this.content = content
    })
  },
  destroyed () {
    events.unsubscribe(events.loyalty.LOYALTY_CONVERT_OPEN)
  },
  beforeMount () {
    events.subscribe(events.loyalty.LOYALTY_CONVERT_OPEN, (force) => {
      this.open(force)
    })
  }
}

</script>

<style lang="scss" scoped>

@use "sass:map";
@use "~@nuskin/ns-core-styles/src/scss/colors";
@use "~@nuskin/ns-core-styles/src/scss/buttons";
@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); // rgb(39, 37, 37)
$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;
    }
  }
}

.ns-convert-popup {
  color: $color-blackhole;
  font-family: ProximaNova;
}

.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>
