<template>
  <div class="d-flex flex-column container">
    <div id="captchaBox" :class="show ? '' : 'hidden'" />
    <vue-hcaptcha
      :sitekey="siteKey"
      challenge-container="captchaBox"
      @opened="show = true"
      @closed="show = false"
      @verify="onVerify"
      @expired="onExpire"
      @challenge-expired="onChallengeExpire"
      @error="onError"
    />
    <v-checkbox
      v-model="honeyPotChecked"
      :rules="[validateCaptchaState]"
      class="hidden-ctrl"
    />
  </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 show: Ref<boolean> = ref(false)

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)

  show.value = false
}

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;
  }
}

.container {
  position: relative;
}

#captchaBox {
  z-index: 1000;
  position: absolute;
  bottom: 140px;
  box-shadow: 2px 2px 1px grey;
  border: solid 1px lightgray;
  background: white;

  @media (min-width: 600px) {
    left: -100px;
  }
}

.hidden {
  display: none;
}
</style>
