<template>
  <altcha-widget
    v-show="widget !== null"
    ref="widget"
    :challengeurl="runtimeConfig.public.challengeUrl"
    :expire="expire"
    debug
  />
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted, type Ref } from 'vue'
import 'altcha'
import { useRuntimeConfig } from 'nuxt/app'

const runtimeConfig = useRuntimeConfig()
const appStore = useAppStore()

// Setup a 15min expiration date for the payload
const expire: number = 15 * 60 * 1000

const emit = defineEmits(['verified'])

const widget: Ref<HTMLElement | null> = ref(null)

const onStateChange = (e: CustomEvent | Event) => {
  if ('detail' in e) {
    const { payload, state } = e.detail
    if (state === 'verified' && payload) {
      emit('verified')
      appStore.setAltchaPayload(payload)
    }
  }
}

onMounted(() => {
  setTimeout(() => {
    if (widget.value) {
      widget.value.addEventListener('statechange', onStateChange)
    }
  }, 10)
})

onUnmounted(() => {
  if (widget.value) {
    widget.value.removeEventListener('statechange', onStateChange)
  }
})
</script>

<style scoped lang="scss">

</style>
