<template>
  <div v-if="show">
    <div
      class="btn_trial"
      :class="{['btn_mini'] : minimized}"
      @click="trialAction()"
    >
      <v-icon icon="fa fa-ticket" />

      <span v-if="organizationProfile.isTrialActive && !minimized">
        <strong>J-{{organizationProfile.trialCountDown}}</strong>
        <br/>
      </span>

      <span v-if="!minimized">{{ btnLabel }}</span>
    </div>

    <LayoutDialogTrialAlreadyDid
      :show="showDialog"
      @closeDialog = "showDialog = false"
    />
  </div>
</template>

<script setup lang="ts">
import UrlUtils from "~/services/utils/urlUtils";
import {useApiLegacyRequestService} from '~/composables/data/useApiLegacyRequestService';
import {computed} from '@vue/reactivity';

const runtimeConfig = useRuntimeConfig()
const accessProfile = useAccessProfileStore()
const organizationProfile = useOrganizationProfileStore()
const { apiRequestService } = useApiLegacyRequestService()
const i18n = useI18n()

const props = defineProps({
  show: {
    type: Boolean,
    required: false,
    default: false
  },
  minimized: {
    type: Boolean,
    required: false,
    default: false
  }
})

const showDialog: Ref<boolean> = ref(false)

const btnLabel = computed(() => {
  if(organizationProfile.isTrialActive){
    return i18n.t('trial_started')
  }
  return organizationProfile.principalType === 'ARTISTIC_PRACTICE_ONLY' ? i18n.t('try_premium') : i18n.t('discover_offer')
})

/**
 * Lorsque l'on appuie sur le bouton pour démarrer l'essai / découvrir les offres
 */
const trialAction = async () => {
  const v1BaseURL = runtimeConfig.baseUrlAdminLegacy || runtimeConfig.public.baseUrlAdminLegacy

  if(organizationProfile.isTrialActive){
    await navigateTo(UrlUtils.join(v1BaseURL, '#', 'subscribe'), {
      external: true
    })
  }else if(organizationProfile.principalType === 'ARTISTIC_PRACTICE_ONLY'){
    try{
      await apiRequestService.get('/trial/is_available')
      await navigateTo(UrlUtils.join(v1BaseURL, '#', 'trial'), {
        external: true
      })
    }catch(error){
      showDialog.value = true
    }
  }else{
    await navigateTo('/subscription')
  }
}

</script>

<style scoped lang="scss">
.btn_trial {
  background-color: rgb(var(--v-theme-x-create-btn));
  border-radius: 5px;
  border: 1px solid #fff;
  margin-left: 15px;
  margin-right: 15px;
  text-align: center;
  color:#000;
  margin-top: 5px;
  padding: 5px 10px;
  cursor: pointer;
  white-space: pre-line;
  font-size: 13px;

  .v-icon {
    font-size: 16px;
    color:#000;
    padding-right: 5px;
    margin: 0 5px 4px 0;
  }
}

.btn_mini {
  font-size: 17px;
  margin-left: 7px;
  margin-right: 7px;
  padding: 0;

  .v-icon {
    padding-right: 0;
    margin: 0 0 3px 0;
  }
}
</style>
