<template>
    <h1>{{ $t('confirmation.title') }}</h1>

    <uiLoading v-if="result === null" />

    <div class="confirm-main-text" v-if="result!=null">
      <div v-if="result === true">
        <p v-if="authStore.isLoggedIn" >{{ $t('confirmation.successConnected') }}
        <NuxtLink :to="localePath('/lists')">{{ $t('confirmation.listsLink') }}</NuxtLink>
        </p>
        <p v-else>{{ $t('confirmation.successNotConnected') }} <NuxtLink :to="localePath('/login')">{{ $t('confirmation.loginLink') }}</NuxtLink></p>
      </div>
    <div v-else>
      <p class="confirm-main-text" v-if="result === 'expired'">{{ $t('confirmation.failureMessage')}}<br/><span>{{ $t('confirmation.failureCauseExpired') }}</span></p>
      <p class="confirm-main-text" v-else>{{ $t('confirmation.failureMessage')}}<br/><span>{{ $t('confirmation.failureCauseInvalid') }}</span></p>
      <p class="confirm-main-text last">{{ $t('confirmation.failureYouCan')}} <NuxtLink :to="localePath('/signup')">{{ $t('confirmation.failureCreateNewAccount') }}</NuxtLink> {{ $t('confirmation.failureOr') }} <NuxtLink :to="localePath('/')">{{ $t('confirmation.backHome') }}</NuxtLink>
      </p>
    </div>
  </div>
</template>

<script setup lang="ts">
definePageMeta({
  layout: 'confirmation',  // utilisation du layout confirm
  public: true,
})
import type { ConfirmResult} from '~/types/auth';
const authStore = useAuthStore()
const localePath = useLocalePath()
const loading = ref<boolean>(true)
const result = ref<ConfirmResult | null>(null)
const userConnected = ref<boolean>(false)

onMounted(async () => {
  const route = useRoute()
  // const user = route.query.user as string
  const token  = route.query.token as string

  if (!token) {
    loading.value = false
    return
  }

  try {
    result.value = await authStore.confirmUser(token)
    if (result.value === true) {
      if (authStore.isLoggedIn && authStore.user){
        authStore.user.confirmed = true;
      }
    }
  } catch {
    throw new Error("Invalid !");
    
  }
  finally{
    loading.value=false
  }
})
</script>

<style scoped lang="scss">

p > span{
  color:red;
  text-align: center;
  display: block;
  margin-block: 1.2em;
  font-weight: bold;
}
.confirm-main-text:first-of-type{
  margin-top: 2em;
}
</style>
