<!-- https://github.com/BillBuilt/sveltekit-hcaptcha -->
<script>
	import { onMount, onDestroy } from "svelte";
	import { browser } from "$app/environment";
	import { HCAPTCHA_SITEKEY } from "$lib/constants";

	let hcaptcha;
	let hcaptchaWidgetID;

	export let token = null;
	// forces 1-way binding
	let captchaToken;
	$: token = captchaToken;

	export let isValid = false;
	// forces 1-way binding
	let captchaValid;
	$: isValid = captchaValid;

	onMount(() => {
		setTimeout(function () {
			if (browser) {
				hcaptcha = window.hcaptcha;
				if (hcaptcha.render) {
					hcaptchaWidgetID = hcaptcha.render("hcaptcha", {
						sitekey: HCAPTCHA_SITEKEY,
						size: "normal",
						callback: onValidCaptcha,
						"error-callback": onErrorCaptcha,
						theme: "light"
					});
				}
			}
		}, 500);
	});

	onDestroy(() => {
		if (browser) {
			hcaptcha = null;
		}
	});

	function onValidCaptcha(e) {
		//console.log('verified event', e)
		captchaToken = e;
		captchaValid = true;
	}

	function onErrorCaptcha(e) {
		//console.log('error event', {error: e.error})
		captchaToken = null;
		captchaValid = false;
		hcaptcha.reset(hcaptchaWidgetID);
	}
</script>

<svelte:head>
	<script src="https://js.hcaptcha.com/1/api.js?render=explicit" async defer></script>
</svelte:head>

<div id="hcaptcha" class="h-captcha" />
