<template>
  <div class="d-flex flex-column">
    <vue-hcaptcha
      :sitekey="siteKey"
      challenge-container="captchaBox"
      @verify="onVerify"
      @expired="onExpire"
      @challenge-expired="onChallengeExpire"
      @error="onError"
    />
    <v-checkbox
      v-model="honeyPotChecked"
      :rules="[validateCaptchaState]"
      class="hidden-ctrl"
    />

    <div id="captchaBox"></div>
  </div>
</template>

<script setup lang="ts">
import VueHcaptcha from '@hcaptcha/vue3-hcaptcha'
import type { Ref } from 'vue'

const runtimeConfig = useRuntimeConfig()
const siteKey = runtimeConfig.public.hCaptchaSiteKey

const verified: Ref<boolean> = ref(false)
const expired: Ref<boolean> = ref(false)
const token: Ref<string> = ref('')
const eKey: Ref<string> = ref('')
const error: Ref<string> = ref('')

// La case étant masquée, si elle est cochée, alors on peut en déduire
// qu'on a affaire un robot (voir mécanisme du honey pot)
const honeyPotChecked: Ref<boolean> = ref(false)

const emit = defineEmits(['update'])

const validateCaptchaState = () =>
  (verified.value && !honeyPotChecked.value) ||
  'Veuillez procéder à la vérification'

function onVerify(tokenStr: string, ekey: string) {
  verified.value = true
  token.value = tokenStr
  eKey.value = ekey
  emit('update', true)
}

function onExpire() {
  verified.value = false
  token.value = ''
  eKey.value = ''
  expired.value = true
}

function onChallengeExpire() {
  verified.value = false
  token.value = ''
  eKey.value = ''
  expired.value = true
}

function onError(err: string) {
  token.value = ''
  eKey.value = ''
  error.value = err
  console.log(`Error: ${err}`)

  if (process.dev) {
    console.log('Dev mode: force captcha validation')
    verified.value = true
  }
}
</script>

<style scoped lang="scss">
.hidden-ctrl {
  :deep(.v-input__control) {
    display: none;
  }
}
</style>
