<template>
  <div class="btn-wrapper">
    <v-btn variant="outlined" @click="onClick">
      {{ $t('download_pdf') }}
    </v-btn>
    <AltchaValidation
      v-if="showCaptcha"
      @verified="onVerified"
    />
  </div>
</template>

<script setup lang="ts">
import type { Ref } from '@vue/reactivity'
import type { ComputedRef } from 'vue'

const appStore = useAppStore()

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

const showCaptcha: ComputedRef<boolean> = computed(() => {
  return downloadRequested.value && !appStore.altchaPayload
})

const onClick = () => {
  if (appStore.altchaPayload) {
    submit()
  } else {
    downloadRequested.value = true
  }
}

const onVerified = () => {
  if (!downloadRequested.value) {
    return
  }
  downloadRequested.value = false
  setTimeout(() => {
    submit()
  }, 100)
}

const submit = async () => {
  const url = 'https://api.ogene.fr/api/download-cv?payload=' + (appStore.altchaPayload ?? '');
  window.open(url, '_blank');
}
</script>

<style scoped lang="scss">
.btn-wrapper {
  position: relative;
  margin: 0 !important;
}

altcha-widget {
  position: absolute;
  top: 50px; /* Ajustez cette valeur en fonction de la hauteur de votre bouton */
  left: 0;
  background: rgb(var(--v-theme-surface));
  border-radius: 4px;
  z-index: 10;
}
</style>