<template>
    <div style="height: 73px" @click="render"></div>
</template>

<script lang="ts">
import { useRuntimeConfig } from 'nuxt/app';
import { defineComponent } from 'vue';
import type { PropType } from 'vue';

import useConfig from '../composables/useConfig.ts';
import useDark from '../composables/useDark.ts';

interface Turnstile {
    render(
        element: Element,
        config: { sitekey: string; theme: 'dark' | 'light'; language: string; callback: (token: string) => void },
    ): void;
}

declare global {
    interface Window {
        turnstile?: Turnstile;
    }
}

export default defineComponent({
    props: {
        modelValue: { default: '', type: String as PropType<string | null> },
    },
    emits: ['update:modelValue'],
    setup() {
        const { detectDark } = useDark();
        return {
            runtimeConfig: useRuntimeConfig(),
            config: useConfig(),
            detectDark,
        };
    },
    async mounted() {
        await this.$loadScript(
            'turnstile',
            `https://challenges.cloudflare.com/turnstile/v0/api.js?render=explicit&language=${this.config.locale}`,
        );
        setTimeout(() => {
            this.render();
        }, 500);
    },
    methods: {
        render() {
            if (!window.turnstile || this.$el.innerHTML.length) {
                return;
            }
            window.turnstile.render(this.$el, {
                sitekey: this.runtimeConfig.public.turnstileSitekey,
                theme: this.detectDark() ? 'dark' : 'light',
                language: this.config.locale,
                callback: this.solved,
            });
        },
        solved(token: string) {
            this.$emit('update:modelValue', token);
        },
    },
});
</script>
